1

Here's my code:

$(document).ready(function() {
    var myArray = [];
    $.getJSON("some url",function(data){
        $.each(data, function(){
            myArray.push("a string" + this);
        });
        alert(myArray);
    });
    //alert(myArray);
});

The code as shown is working just fine and it displays the array and its contents.

However, when I try to display the array by having the command line right after the $.each code block (commented out in the sample code), the array and its contents are not displayed. An empty/ blank message is returned instead.

Why is this happening and how can I fix it? I'd like to have the command "alert(myArray);" right after the $.each block.

Thank you in advance!

Mohammad
  • 21,175
  • 15
  • 55
  • 84
ApollonCY
  • 11
  • 2
  • 4
    Ajax is asynchronous. You must use the data returned inside the callback, not outside. It can't be fixed without moving to `async: false`, but that's a terrible idea. – Kevin B Apr 18 '13 at 18:51
  • The second alert runs BEFORE the json is taken from the server, so it is empty. – Rafael Herscovici Apr 18 '13 at 18:51
  • 2
    This is one of the most common questions on this site. See [this answer](http://stackoverflow.com/a/14220323/778118) for more info about what you're experiencing. – jahroy Apr 18 '13 at 18:54
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – jahroy Apr 18 '13 at 18:55
  • The first blank is because getJson have not return yet so the array is still emptied. You didn't see the alert inside the getJSON because first alert is blocking the alert inside the getJSON. – Du D. Apr 18 '13 at 19:07
  • In addition to the other comments, don't use `alert` for debugging. Use `console.log` instead. This will avoid timing dependencies caused by `alert`. – Michael Geary Oct 17 '16 at 04:07

1 Answers1

0
var myArray = [];
var jqxhr = $.getJSON( "some url", function(data) {
  $.each(data, function(){
     myArray.push("a string" + this);
  });
})  ;

jqxhr.complete(function() {
  console.log(myArray);
});

jQuery XHR object, or "jqXHR," is returned by $.getJSON()

When the request is already complete, the .complete() callback is fired immediately.

Neethu George
  • 587
  • 5
  • 8