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

6
  • 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 Commented Jul 23, 2014 at 11:18
  • 2
    Don't pollute the global scope with variables. Pass a callback into test() instead Commented Jul 23, 2014 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! Commented Jul 23, 2014 at 11:20
  • How to return the response from an Ajax call Commented Jul 23, 2014 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. Commented Jul 23, 2014 at 11:23

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I want data to use is several other functions.. if i did so, will this send json request to server each time?
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"?
any possible way to cache the data or preload first time and use?
My edit allows you to cache the data in myData - a variable that is global but only to that closure.
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'   
}

1 Comment

+1 for showing how the async call results in undefined. That's the pattern I was using and not understanding why undefined results.
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
});

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.