So after 6+ hours of searching and trying out various solutions, I have only been able to log "undefined" at console.log(diseaseNameArray). I am very new to javascript, and cannot figure out why this is not logging a populated array. I greatly appreciate any help/advice you have to give. Any other additional critiques of code are 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 Jan's point, I am back at the drawing board to get this to work. If anyone has a suggestion I would greatly appreciate it!
Ajax is asynchronous. You are calling populateArray and then immediately logging diseaseNameArray to the console before the ajax request completes, so of course it's going to be undefined -- you're not giving the ajax request time to complete. You need to log to console in success.
Or make the ajax call synchronous with async: false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With