assigning data from $.getJSON() to a global variable?

Showing 1-3 of 3 messages
assigning data from $.getJSON() to a global variable? funkadelic 3/27/08 4:18 PM
Hi,

Is there a way to take the JSON from a $.getJSON() call and assign it
to a var in the global scope?

i tried the following but it didn't work:

var globalX;

function foo() {
  $.getJSON("jsondata.js",function(data){
    globalX = data;
  });
}

thanks
RE: [jQuery] assigning data from $.getJSON() to a global variable? Michael Geary 3/27/08 5:43 PM
That should work just fine. However... You didn't show the code that tries
to use the globalX variable, and that is probably where the problem lies.
Does the overall flow of your code look like this perhaps?

var globalX;

function foo() {
  $.getJSON("jsondata.js",function(data){
    globalX = data;
  });
}

alert( globalX );

That won't work, because the alert() is called *before* the asynchronous
getJSON callback.

OTOH, this would work:

var globalX;

function foo() {
  $.getJSON("jsondata.js",function(data){
    globalX = data;
    dataReady();
  });
}

function dataReady() {
    alert( globalX );
}

Now the alert() is called after the globalX data is ready.

But since you have to use a callback like this anyway, you may not need the
global variable at all. After all, this code:

function foo() {
  $.getJSON("jsondata.js",function(data){
    alert( data );
  });
}

would obviously work, as would this:

var globalX;

function foo() {
  $.getJSON("jsondata.js", dataReady);
}

function dataReady( data ) {
  alert( data );
}

-Mike

Re: assigning data from $.getJSON() to a global variable? funkadelic 3/31/08 11:23 AM
thanks Mike! my code was actually within a JS function that is
supposed to return a value & i forgot about the "A" in ajax :)

i ended up using $.ajax() to force the ajax request to be synchronous
so that it would get the value from the ajax request, but I set the
$.ajax() option async to "false" (with the quotes). i kept banging my
head until I realized that I wrapped the boolean false in quotes.
removed the quotes, everything worked, and banged my head a little
more for making a simple mistake ;)

thanks,
-norm