I'm getting JSON through AJAX and pushing parts of the result to an array that was declared before the AJAX request. When I console.log() the queriesTop variable here once the array.push is done, it returns an empty array even if there AJAX response has JSON data. Why is this? I read somewhere else that because it is asynchronous, other code runs before the AJAX call returns the data but here, I am using the .done() function with a callback to pushQueries. Why is it still not functioning? How do I fix this?
function getQueries() {
var queriesFailed = [],
queriesTop = [];
$.ajax({url: "getStats"}).done(function(data) {
pushQueries(data);
});
function pushQueries(data) {
var resultsFailed = data['query']['failed']['queries'],
resultsTop = data['query']['top']['queries'];
for (var i = 0; i < resultsFailed.length; i++) {
queriesFailed.push(resultsFailed[i]);
};
for (var i = 0; i < resultsTop.length; i++) {
queriesTop.push(resultsTop[i]);
};
}
console.log(queriesTop);
return queriesTop;
}