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:
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.');
}
});