Returning an array from javascript
So after 6+ hours of searching and testing various solutions, I was able to log "undefined" to console.log (diseaseNameArray). I'm very new to javascript and can't figure out why this doesn't register a populated array. I really appreciate any help / advice you have to give. Any other additional criticism is also appreciated.
var diseaseNameArray;
var jax = $.ajax;
/*OutputHandler*/
function outputHandler(data, arrayTarget, tag, length) {
var source = $(data); /*holder of xml*/
var lengthStorage = Number(source.find(length).text()); /*length of list*/
arrayTarget = []; //array to be populated
for(i = 1; i < lengthStorage; i++)
{
arrayTarget[i] = source.find(tag + i.toString()).text();
console.log(arrayTarget[i]); //to check that elements are being entered
}
console.log(arrayTarget); //succesfully logs the full array
}
/*General function*/
function populateArray(xmlLocation, typeOfData, tag, lengthStorage, extFunction, targetArray) {
$.ajax({
type: "GET",
url: xmlLocation,
dataType: typeOfData,
success: function(xml)
{
extFunction(xml, targetArray, tag, lengthStorage);
},
error: function()
{
console.log("ugh");
}
});
}
populateArray("malePatient.xml", "xml", "sub", "length", outputHandler, diseaseNameArray);
console.log(diseaseNameArray);
Update Thanks to the January point, I went back to the drawing board to get it working. If anyone has a suggestion I would really appreciate it!
source to share
Ajax is asynchronous. You call populateArray
and then immediately write diseaseNameArray
to the console before the ajax request completes, so of course it will be undefined - you are not giving the time of the ajax request. You need to log into the console at success
.
Or make the ajax call synchronous with async: false
.
source to share
AJAX stands for A Synchronous J avashcript A nd X ml. Since it is asynchronous, your data doesn't have to reach your function outputHandler
. You should probably create a function that runs after outputHandler
and is called at the end outputHandler
. You should put yours console.log
in this second function. Thus, the receipt of data is guaranteed.
Either that, or you can pipe async: false
to the AJAX call to make it synchronous so that the console.log appears after outputHandler
. But, if the AJAX call fails, then console.log will still be called and it will exit undefined.
source to share