1

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Rohit
  • 6,941
  • 17
  • 58
  • 102

1 Answers1

1

Your code is updating the global variable. The function that sets the value is called after the alert statement in your code. The JavaScript code is not waiting for the result of the execution of the microAjax call. To check if the microAjax method returns successfully put the alert method after the assignment:

var load_values_from_server = "initial value";

microAjax("http://domain.com/show-server-load.php?" + randomnumber, 
  function (results) { 
    load_values_from_server = results;            
    alert(load_values_from_server); 
  });

microAjax does not give you much configuration possibilities. Look at this SO question and answers to perfrom a synchronous request using jQuery.

Community
  • 1
  • 1
Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32