0

Possible Duplicate:
jQuery AJAX: return value on success

Im having this weird reference issue when im trying to get a JSON file through query:

    var themeData;
    $.getJSON("json/sample.js", function(data) {
                themeData = data.theme;
                        console.log(themeData.sample[0].description);
            }); 
   console.log(themeData.sample[0].description);

The first console.log works, the second doesnt. Why is this happening?

Community
  • 1
  • 1
Carlos R. Batista
  • 135
  • 1
  • 4
  • 11

2 Answers2

5

It's the second one (chronologically in your code) that doesn't get hit. That's because it hasn't been set yet. The callback inside getJSON gets invoked asynchronously after returning from the server.

var themeData;

// FIRST -- themeData currently null
$.getJSON("json/sample.js", function(data) {

    // THIRD -- now themeData has a value, and gets logged
    themeData = data.theme;
    console.log(themeData.sample[0].description);
}); 

// SECOND -- themeData still null
console.log(themeData.sample[0].description);

If you really need to call a method "after" getJSON, then embrace the idea of callbacks. Use something like this.

var themeData;
function myCallback(data) {
    console.log(data.sample[0].description);
}
$.getJSON("json/sample.js", function(data) {
    themeData = data.theme;
    console.log(themeData.sample[0].description);
    myCallback(themeData);
}); 

Edit

You could also force a synchronous call instead using async: false of the JQuery ajax function.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  async: false
});
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • ugh, but this solution will only limit the scope to this particular callback function. I kinda need to have access to this information through out the whole document. Is there a different approach I should consider instead? – Carlos R. Batista Oct 03 '12 at 04:05
  • @CarlosR.Batista See my update above -- you could force it to be a synchronous call, and then your code would work. Synchronous calls should really be used sparingly though, as they block the client script while waiting for the server. – McGarnagle Oct 03 '12 at 04:12
  • well the thing is, im only pulling this json file once while the client will spend about 30 minutes on the same page(its a web app) flipping through all the data I already pulled. The other option would be to make an ajax call every single time I need a piece of data from this file which didnt seem too efficient to me. Im guessing async is the right call in this case right? – Carlos R. Batista Oct 03 '12 at 04:40
  • @CarlosR.Batista yes, sounds like it should be fine. – McGarnagle Oct 03 '12 at 04:41
0

No, $.getJSON is a async method, when the second console.log is called, there's no themeData at that time.

Marcus
  • 6,701
  • 4
  • 19
  • 28