5

jQuery

I am making an AJAX request that updates the value of a variable (foo) with a response from the server. Here is the code I am using:

//## My variable ##

var foo = "";


//## Send request ##

$.ajax({
    url: "/",
    dataType: "text",
    success: function(response) {
        foo = "New value:" + response;
    },
    error: function() {
        alert('There was a problem with the request.');
    }
});


//## Alert updated variable ##

alert(foo);

The problem is that the value of foo remains an empty string. I know that this is not a problem with the server-side script, since I would either get an error alert or at the very least the string "New value:".

Here is a JSFiddle that demonstrates the problem: http://jsfiddle.net/GGDX7/

Why is the value of foo not changing?


Pure JS

I am making an AJAX request that updates the value of a variable (foo) with a response from the server. Here is the code I am using:

//## Compatibility ##

var myRequest;
if (window.XMLHttpRequest) {
    myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}


//## My variable ##

var foo = "";


//## Response handler ##

myRequest.onreadystatechange = function() {
    if (this.readyState === 4) {
        if (this.status === 200) {
            foo = "New value:" + this.responseText;
        } else {
            alert('There was a problem with the request.');
        }
    }
};


//## Send request ##

myRequest.open('GET', "response.php");
myRequest.send();


//## Alert updated variable ##

alert(foo);

The problem is that the value of foo stays an empty string. I know that this is not a problem with the server-side script, since I would either get an error alert or at the very least the string "New value:".

Here is a JSFiddle that demonstrates the problem: http://jsfiddle.net/wkwjh/

Why is the value of foo not changing?

Community
  • 1
  • 1
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • Related: http://meta.stackexchange.com/questions/157942/creating-generalized-questions-for-trivial-errors-in-order-to-be-able-to-close-a/158211 – Asad Saeeduddin Dec 14 '12 at 17:51
  • The callbacks are asynchronous, if you don't know what that means, read up on it http://recurial.com/programming/understanding-callback-functions-in-javascript/ – Ruan Mendes Dec 14 '12 at 17:56
  • 1
    @JuanMendes I know what asynchronous means. I am asking this as a generalized reference question because of the number of dupe spinoffs we have on this topic. See the meta question I have linked. – Asad Saeeduddin Dec 14 '12 at 17:59
  • Yeah... I was wondering... does somebody with 12.8k really not know what's going on here? – Ruan Mendes Dec 14 '12 at 18:00
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – user229044 Jul 04 '13 at 12:35

5 Answers5

5

At the point when you alert the value of foo, the success handler has not yet fired. Since it is the success handler that reassigns the variable, its value remains an empty string.

The timeline of events looks something like this:

  1. foo is assigned the empty string
  2. AJAX request created and dispatched.
  3. The value of foo is alerted. (Note that foo hasn't changed yet)
  4. AJAX request completes.
  5. foo = "New value:" + this.responseText;

Since we want to alert the value of foo after it has changed, the solution is to put the alert in the success callback.

Now it will be executed after the AJAX response is received.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3

The (first) A in "AJAX" stands for asynchronous. The transaction does not happen immediately, and so your alert() happens quite some time before the remote call completes.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

The problem is that your alert is being fired before the request has been completed. Try this code:

I've put the alert into the callback function of the $.ajax, which means that the callback function will only be fired after the .ajax part has been completed. This will transfer the new data over, set the variable, THEN alert it, rather than calling the request and alerting the variable at the same time.

$.ajax({
    url: "/",
    dataType: "text",
    success: function(response) {
        foo = "New value:" + response;
        alert(foo);
    },
    error: function() {
        alert('There was a problem with the request.');
    }
});
Felix Guo
  • 2,700
  • 14
  • 20
0

The issue is simple...

alert(foo);

will execute while the request is being processed and foo will not be altered yet.

if you do :

$.ajax({
    url: "/",
    dataType: "text",
    success: function(response) {
        foo = "New value:" + response;
        alert(foo);
    },
    error: function() {
        alert('There was a problem with the request.');
    }
});

You'll see that it's working as intended

Polyana Fontes
  • 3,156
  • 1
  • 27
  • 41
0

Your alert is executing before the Ajax request is finished. Try the following. var foo = "";

$.ajax({
    url: "/",
    dataType: "text",
    success: function(response) {
        foo = "New value:" + response;

        alert(foo);
    },
    error: function() {
        alert('There was a problem with the request.');
    }
});
Carlos Nuñez
  • 470
  • 1
  • 3
  • 12