I would like to save the json response in a global variable, so I could use it through my application 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 register it in the actual request, it will be fine, but I get "undefined" everywhere. Any comment is appriciated.
Edit [copied from comments]: I 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 fine, the second is undefined.
Edit [copied from answer]:
in fact both methods worked
Interestingly, my request was in a function, and I tried to access my global variable after the request in the same function
when i got it out of function it worked like a charm
source share