0

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;
}
JackH
  • 4,613
  • 4
  • 36
  • 61
  • I pointed out what you already found. This is common question, see the duplicate. – elclanrs Jul 27 '14 at 07:03
  • It is because of the asynchronous nature. Your ajax call executes and then, before it can even return, your console.log and return statement run. Put those *inside the callback function* (e.g. pushQueries basically) if you need them to run after you've gotten the data back. – phette23 Jul 27 '14 at 07:04
  • It says 'unexpected return' if I put the return statement inside the AJAX request. – JackH Jul 27 '14 at 07:13
  • @Nagarjun You have to move there `console.log(queriesTop)`, not `return` statement – hindmost Jul 27 '14 at 07:19
  • I need the console.log() outside. Basically, I need to return the array. That is why I have it outside the AJAX request – JackH Jul 27 '14 at 07:31

0 Answers0