How to update globale variable from within a callback function?

Hello,

I have a problem where I am not able to update a global variable from inside a callback function.

Here is my code:

// Set global variable.
var load_values_from_server = "initial value";

// Call our page that shows server load and put it into "results" variable.
microAjax("http://domain.com/show-server-load.php?" + randomnumber, 
 function (results) { 
    load_values_from_server = results; 
 });

// We want this to show the "results" from the callback function.
alert(load_values_from_server);

The problem is that the alert always shows “initial value” and never the “results” from the callback function.

What am I missing? Shouldn’t global variables be global, even within a callback function?

Thanks!

It seems that you may have a fundamental misunderstanding when it comes to Ajax.

Ajax calls are set aside for some later time. The script carries on executing its code, and later on after Ajax has requested its content and received a response, only then (which is a long time after the rest of the script has finished) does the associated Ajax function get run.

So if you want to do something with the result in the callback function, it is inside of that callback function that you should do it, which can include calling other functions that you need too.


Source: http://fixingthesejquery.com/#slide40

Thanks! That makes perfect sense and I was able to figure out how to make this work.

Nice and simple. Here is the new code:


// Set global variable.
var load_values_from_server = "initial value";
 
// Call our page that shows server load and put it into "results" variable.
microAjax("http://domain.com/show-server-load.php?" + randomnumber, 
 function (results) { 
    show_results(results);
 });
 
function show_results(results) {
 // We want this to show the "results" from the callback function.
 alert(load_values_from_server);
}