Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign data from jQuery getJSON to array

Tags:

jquery

getjson

How do you assign the data fetched via getJSON() to an array, for later use?

The getJSON url below retrieves properly formatted JSON with 10 main elements, each having subelements of id, username, haiku (and other). If you're running it, try saving the JSON elements to a local file, so you won't get the same domain error (i.e., JSON will not load if you're fetching from a different domain).

What happens is that the alert will fetch a value within the getJSON callback, but outside, the value is undefined.


$(document).ready(function(){
    var haikus=[];
    alert("begin loop");
    $.getJSON('http://example.com/json.php',function(data){
         var i=0;
         for(i=0;i<data.length;i++){
            haikus[i]=[data[i].id,String(data[i].username),String(data[i].haiku)];
        }
            alert(haikus[0][1]);
    });
})

  • Yes, this is related to a previous post. But, I'd initially simplified my problem too much, so the initial solutions provided did not solve it. jQuery - getJSON data to array
like image 475
ina Avatar asked Nov 30 '22 10:11

ina


1 Answers

Your issue is that any code outside (and after) the $.getJSON request has already run by the time the $.getJSON response is received.

Remember that AJAX calls are asynchronous. This means that the code following the AJAX request does not wait for the response to execute. So it runs long before there's any response.

The key is that any code that relies on the response from an asynchronous AJAX request, must run (or be called from) inside the callback.


EDIT:

To clarify, in the code example below, please see the code comments. It should help explain the issue.

$(document).ready(function(){
    var haikus=[];
    alert("begin loop");
    $.getJSON('http://haikuennui.com/random.php',function(data){
         var i=0;
         for(i=0;i<data.length;i++){
            haikus[i]=[data[i].id,String(data[i].username),String(data[i].haiku)];
        }
                 // The data in haikus is available here becuase
                 //    this alert() doesn't run until the response is received.
            alert(haikus[0][1]);
    });

         // Here the data in haikus is NOT available because this line
         //     of code will run ***before*** the response from the AJAX
         //     request from above is received.
         // In other words, this alert() executes **immediately** without
         //     waiting for the $.getJSON() to receive its response.
    alert(haikus[0][1]);

});
like image 52
user113716 Avatar answered Dec 05 '22 16:12

user113716