0

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?

Chris
  • 57,622
  • 19
  • 111
  • 137
pythonic
  • 20,589
  • 43
  • 136
  • 219

2 Answers2

3

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)
 });
Chris
  • 57,622
  • 19
  • 111
  • 137
2

You can try this

var globalVar = false;

jQuery.ajax({
    type: "GET",
    url: 'some.php',
    success: function (data) {
    globalVar = true;
    }, 
    async: false // <- this turns it into synchronous
});​

alert(globalVar);

I update the better way in this case

var globalVar = false;

function getData(callback) {
    $.ajax({
        url: 'jsOnChange.php',
        type: 'GET',
        success: callback
    })
}
getData(function(response) {
    globalVar = true;
    console.log(globalVar);
});
Quynh Nguyen
  • 2,959
  • 2
  • 13
  • 27