Question

I'd like to store my json response in a global variable so, i could use it through my app without making a getJSON request more than once.

var data;
$.getJSON("panorama.json",function(json){
data = json.images[0].src;
console.log(data);          
});


console.log(data);

If I log it in the actual request its fine, but i get "undefined" everywhere else. Any comment appriciated.

Edit [copied from comments]: Tried ...

$.myglobals = { result: "unset" } 

$(document).ready(function() { 

  $.getJSON( "panorama.json", function(json) { 
    $.myglobals.result = json.images[0].src; 
    console.log($.myglobals.result);     
  });

  console.log($.myglobals.result); 
}) ;

The first log is okay, the second is undefined.

Edit [copied from answer]:

actually both method worked

the interesting thing is that my request was in a function and i tried to acces my global variable right after the request in the same function

when i accesed it outside the function it worked like a charm

Was it helpful?

Solution

If your real code is structured like that then you have a problem with trying to access the data that hasn't been set yet. Just because your $.getJSON() is above console.log() doesn't mean that you get the response before you log value of data.

So your problem is not scope, but rather the timing: introduce some server-side lag and your solution may as well crash.

Maybe you should set some flag if response was received:

var data, dataReceived = false;

$.getJSON("panorama.json",function(json){
  data = json.images[0].src;
  dataReceived = true;
  console.log(data);                    
});


// somwhere later
if (dataReceived) {
  console.log(data);
} else {
  // you could use setTimeout() or setInterval here to re-check
  console.log("data not received yet");
}

OTHER TIPS

You could insert it into an attribute in the DOM (such as an #ID) and retrieve it as needed.

Here is an approach that lets you set the variable in one $(document).ready() and use it in a different $(document).ready(). myglobals is a namespace object which arguably reduces the chances of your global variable colliding with someone else's, especially if you name it something more clever than "myglobals."

$.myglobals = {
  result: "unset" 
}

$(document).ready(function() {

  function pretend_JSON_call() {
    $.myglobals.result = {'a':"hello", 'b':"world" };
  }

  pretend_JSON_call();
});

$(document).ready(function() {
  alert($.myglobals.result['a']);
  alert($.myglobals.result['b']);
});

Transient link to the above code in jsbin.

$.getJSON fires an ajax request (the keyword in the scope of the question being asynchronous).Your variable is undefined because it hasn't been define yet, the response hasn't finished. Other people suggested moving your console.log further down in your code, but there's no guarantee it will be usable unless your logic is synced with a callback function. $.getJSON accepts a callback function as one of its parameters.

$.getJSON( "myData.json", function( data ) {
    //Do whatever, this is a callback
    $.each( data, function(key, val) {
       //You can get even more specific like so
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top