Jquery.getJSON() assigning JSON returned to an array/var outside callback function

Hello everyone,

I’m trying to assign the values from the JSON data returned when I run this code into an array that’s outside the callback function. The data is multidimensional, and I have been able to use this data within the callback function. However I want to use it outside that function.

i.e. the jsdata returned in the code below is to be used outside the function

$.getJSON('../fxns/status.php',function(jsdata){

//do some stuff with JSON data or pass to global variable

});

I’ve tried something like this:

var j = $.getJSON('../fxns/status.php',function(jsdata){});

var myarray = j.responseText;
alert(myarray.length);

but it returns nothing.

Ideas, anyone?

The myarray variable is not a global variable. You can use the window object to effectively create a global variable. Using the window object is useful because when you’re later on looking through your code, there will be no confusion over whether the variable is global or not. As a window object, it’s always global.

Place the following inside the callback, and you should be fine.


window.myarray = j.responseText;

I’ve just tried that and it gives the same result. The variable still isn’t being set from inside the callback function.

let me illustrate what I mean:

window.arr = "something";
$.getJSON('../fxns/status.php',function(jsdata){ window.arr = "something else"});

alert(window.arr);

This still alerts “Something”

I also tried this


$.getJSON('../fxns/status.php',function(jsdata){ window.arr2 = "something else"});

alert(window.arr2);

This alerts “undefined”.

Now, the $getJSON() is meant to return a XMLHttpRequest object, but for some reason it’s properties are only accessible from inside the call back function, and I can’t seem to assign the responseText to any variable outside it.

even

alert($.getJSON('../fxns/status.php').responseText);

alerts a blank dialog box.

When you alert the variable, that is occurring before the information has been set.

That happens because the callback function is delayed until a later stage (when the information is successfully retrieved) whereas the code that does the alert is run straight away, effectively before the callback has had a chance to be called.

The alert section needs to be triggered from the callback in some way, either directly from with, or by having the callback run a function that contains the alert.