Your Ajax call is asynchronous. That means it starts when you execute it here and it finishes sometime later. You must put any code that uses the result of the ajax call inside the success
handler or in a function that you call from the success handler and pass the data to.
An asynchronous operation in Javascript finishes at some future indeterminate time. Meanwhile, the following lines of code continue to execute (before the Ajax code finishes). Then, sometime LATER, after the current thread of execution is done and when the result comes back from the server that the Ajax call was sent to, the success handler for the Ajax call is called and that code executes.
Here's how you consume the result of the ajax call inside the success
handler:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "works.xml",
dataType: "xml",
success: function(xml) {
var infoArray = xmlParser(xml)
$("#test").text(infoArray.length);
}
});
});
function xmlParser (xml) {
//do some push
//I have a test here to make sure that the length of the array is what I want
return Array;
}
In case you didn't know, the first "A" in "Ajax" stands for Asynchronous.
FYI, it is worth learning how to use promises for asynchronous operations. jQuery automatically builds promises for its ajax operations so you can execute the above code using promises like this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "works.xml",
dataType: "xml"
}
}).then(function(xml) {
var infoArray = xmlParser(xml)
$("#test").text(infoArray.length);
}, function(err) {
// handle errors here
});
});
It doesn't look a whole lot better here, but if you start sequencing multiple asynchronous operations or have nested asynchronous operations or want to wait until multiple asynchronous operations are done, promises can make all that a whole lot simpler.
And, promises are built into ES6 so you will see more and more code using them over time.