JavaScript get data from json to a global variable JavaScript get data from json to a global variable jquery jquery

JavaScript get data from json to a global variable


Don't try to set myData as a global variable - it won't work because getJSON is asynchronous. Either use a promise:

function test() {  return $.getJSON('notebook-json-data.php');}$.when(test()).then(function (data) {  console.log(data);});

Or a callback:

function test(callback) {  $.getJSON('notebook-json-data.php', function (data) {    callback(data);  });}test(function (data) {  console.log(data);});

Edit

Since you want to use the data in other areas of your code, use a closure to create an environment where your variables don't leak out into the global space. For example, with the callback:

(function () {  var myData;  function test(callback) {    $.getJSON('notebook-json-data.php', function (data) {      callback(data);    });  }  test(function (data) {    myData = data;    autoPopulate('field', 'id');  });  function autoPopulate(field, id) {    console.log(myData);  }});

myData is cached as a global variable specific to that closure. Note the other functions will only be able to use that variable once the callback has completed.


Instead of creating global variables, it's better to call a callback on "done", like this:

$.getJSON( "example.json", function(data) {    console.log( "json loaded" );    foo(data); }).done(function() {   console.log("");   foo1(data);});

For more information, getJSON API.

The problem is that getJSON is asynchronous, so while getJSON is processing data, the execution of your code goes on.

function test(a){    $.getJSON( "notebook-json-data.php", function( data ) {       a = data;    }}var main = function() {  var a;   test(a);         /* asynchronous */  console.log(a);  /* here, json could be hasn't already finish, most likely, so print 'undefined'   }


You can make use of callback in order to get the data out of the success block

function test(callback){    $.getJSON( "notebook-json-data.php", function( data ) {       callback(data);    } }test(function(data){  //Use your data here});