pythonic pythonic - 1 year ago 48
jQuery Question

How to use a global variable with jquery?

I have a code as shown below.

var globalVar = ''
$.get("some.php", function(data, status)
{
alert(data)
globalVar = data
});
alert(globalVar)


While the first alert shows the value of data, the second alert doesn't. It seems like globalVar was not properly assigned inside the get's function. What would be the proper way to use a global variable here?

Answer Source

What probably happens is that your get() function doesn't finish before your last alert() is being called. To make sure these happen in order, you can put the last alert() in a callback once the file is received.

So try this instead:

 var globalVar = ''
 $.get("some.php", function(data, status)
 {
   alert(data)
   globalVar = data
 }).done(function() {
   alert(globalVar)
 });