tags:

views:

173

answers:

2

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]);
    });
})

A: 

I believe if you define a variable by using 'var haikus = something', the variable is of local scope, and if you define the variable by using 'haikus = something', it is of global scope.

kevtrout
I'm pretty sure simply doing haikus=something will give you a haikus not defined error, to do it in global scope, just define var haikus = something out side of any functions.
Razor Storm
ahhh!! so my problem has to do with variable scoping (doh)
ina
just tried declaring haikus=[] outside of the readyfunction - the alert both inside the readyfunction but outside the getjson still returns undefined... (rather, does not even pop up)
ina
@Razor - `haikus=something` will give you a global variable. But a global is unnecessary since `haikus` is in the proper scope.
patrick dw
+1  A: 

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]);

});
patrick dw
yes, but what if you populate a global array within the callback - can you reference the array later?
ina
@ina - yes, of course. See this example: http://jsfiddle.net/FgV8W/ If you click the value while the JSON is loading you will get nothing, if you click it after it is done, it will give you your data.
Ryley
@ina - It doesn't matter if it is global or not. If you are trying to use it *before* it has any data, then it will be `undefined`. If you are immediately trying to use the `haikus` variable *outside* the `$.getJSON` callback, it will not work. The code that is using `haikus` *will not wait* for the response to be returned. It will try to use `haikus` *immediately*. Because it does not wait for the response, then `haikus` will have not yet been assigned the `data` from the response.
patrick dw
@Ryley ahh i think i understand what's going on - so basically the json hasn't been loaded before the alert's called (?) Corollary questions - See Discussion on your jfiddle - http://jsfiddle.net/FgV8W/
ina
@ina - That is correct. If you have further questions, please leave comments here.
patrick dw
@Ryley thanks! i have a better understanding of j/s json/ajax data flow now! (btw - i just used the random.php as an easy source of diverse json elements. can you unreference that to http://exampler.com/json.js)
ina
I think I learned the most from this question today on stack overflow than any other! Without even knowing that I had this problem too.
kevtrout