I have a globally-declared array in my function that I want to push elements from an AJAX call to.
AJAX call:
function getDatesFromAJAX() {
return $.ajax({
type: "GET",
url: "http://localhost:8080/api/dates/1",
success: function(dates) {},
error: function(xhr) {
alert("Request status: " + xhr.status + " Status text: " + xhr.statusText + " " + xhr.responseText);
}
});
}
var dateArray = new Array();
// populate dateArray
$.when(getDatesFromAJAX().done(function(dates){
$.each(dates, function (index, date) {
dateArray.push(date);
});
console.log("DATE ARRAY INSIDE FUNCTION: ", dateArray);
console.log("DATE ARRAY LENGTH INSIDE FUNCTION: ", dateArray.length); // 2 (expected)
}));
console.log("DATE ARRAY OUTSIDE FUNCTION: ", dateArray);
console.log("DATE ARRAY LENGTH OUTSIDE FUNCTION: ", dateArray.length); // 0
Although the dateArray outside of the function maybe contains something, it has no length so I can't iterate over it. I think it may not be populating properly due to the nature of AJAX calls, considering the line 'console.log("DATE ARRAY OUTSIDE FUNCTION: ", dateArray)' gets printed before the DATE ARRAY INSIDE FUNCTION lines.