Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get data from json to a global variable

function test(){
    $.getJSON( "notebook-json-data.php", function( data ) {
       var myData = data;
    });
 }

Here in my function i get json objects, but i want to access myData variable from out side the scope of its function.

I have tried setting var myData outside the function but no luck.. :(

I am not familiar with JSON, did i need any parsing?

how to set this variable as global??

Please help...

like image 461
Hareesh Avatar asked Jul 23 '14 11:07

Hareesh


People also ask

How can I get data from JSON to variable?

var json = (function () { var json = null; $. ajax({ 'async': false, 'global': false, 'url': my_url, 'dataType': "json", 'success': function (data) { json = data; } }); return json; })(); The main issue being that $.

How do you assign data from fetch to a variable?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

Can we convert JSON to array?

Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.


2 Answers

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.

like image 57
Andy Avatar answered Sep 28 '22 03:09

Andy


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'   
}
like image 22
Luca Davanzo Avatar answered Sep 28 '22 01:09

Luca Davanzo