14
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...

Hareesh
  • 6,770
  • 4
  • 33
  • 60
  • 1
    `var myData` outside the function, no repetition of `var` inside the function (this would create a new shadowed `myVar`). Bear in mind the call is asynchronous so you can't simply access it after the `getJSON` call – Alex K. Jul 23 '14 at 11:18
  • 2
    Don't pollute the global scope with variables. Pass a *callback* into `test()` instead – CodingIntrigue Jul 23 '14 at 11:18
  • 1
    You can set it to a global all you want, it stil won't be accessible outside the callback as ajax is **asynchronous**! – adeneo Jul 23 '14 at 11:20
  • [**How to return the response from an Ajax call**](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – adeneo Jul 23 '14 at 11:21
  • There might be case that you are trying to read variable before getJSON method finished with reading JSON. It is async call. You need to wait until this function completes its process. – Pramod S. Nikam Jul 23 '14 at 11:23
  • Also, you're missing a closing `)` in your code. – Andy Jul 23 '14 at 11:24

4 Answers4

16

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.

Andy
  • 61,948
  • 13
  • 68
  • 95
  • I want data to use is several other functions.. if i did so, will this send json request to server each time? – Hareesh Jul 23 '14 at 11:28
  • `function autoPopulate(field,id){ test(function (data) { myData = data; console.log(myData); }); } ` when i call the function several times in my html,is a request send to the server each time to load "notebook-json-data.php"? – Hareesh Jul 23 '14 at 13:29
  • any possible way to cache the data or preload first time and use? – Hareesh Jul 23 '14 at 13:35
  • My edit allows you to cache the data in `myData` - a variable that is global but only to that closure. – Andy Jul 23 '14 at 13:43
6

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'   
}
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
  • +1 for showing how the async call results in undefined. That's the pattern I was using and not understanding why undefined results. – matt wilkie Jan 10 '17 at 00:09
4

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
});
V31
  • 7,626
  • 3
  • 26
  • 44
1

Declare a global json object

var APP = APP || {}

Now u can set the dynamic data to that object using

APP.myData = data;

You can get this anywhere in your js file. by using

APP.myData

Jagadeesh
  • 570
  • 3
  • 11