Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store JSON response in jQuery?

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

like image 746
soda01 Avatar asked Jan 23 '23 12:01

soda01


1 Answers

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");
}
like image 148
Damir Zekić Avatar answered Jan 29 '23 14:01

Damir Zekić