George Newton
George Newton

Reputation: 3293

Jquery: Variable not initialized in callback?

I have the following code snippet in Javascript-Jquery:

var result = "";
$.ajax({
    type: 'POST',
    url: 'update.php',
    data: { 'val': $val }
})
.done(function(data) {
    alert(data); // shows right response
    result = data;
    alert(result); // shows right response
});
alert(result); // shows nothing

Even though I initialized result in the callback, I get nothing when I alert the result variable (it is still "")? Why is this?

Upvotes: 2

Views: 335

Answers (3)

user2228392
user2228392

Reputation: 404

This becasue the mode of ajax now you use is the Asynchronous ...i have a example for you that it's as follow:

var result = "";
$.ajax({
type: 'POST',
url: 'update.php',
data: { 'val': $val' }
}).done(function(data) {
     alert(1, data);   // shows right response
     result = data;
     alert(2, result); //shows right response
});
alert(3, result) // shows nothing

if you want to use the Synchronous...look at the doc for async variable i hope it's useful to you:)

Upvotes: 1

Bernardo Pacheco
Bernardo Pacheco

Reputation: 1445

Is is simple. The alert(result) code is executed before the done callback. So, the result variable is empty. The done callback is called asynchronously after the alert call.

Hope it helps.

Upvotes: 1

Kenny Thompson
Kenny Thompson

Reputation: 1492

This is because the ajax call is run asynchronously. Just because the second alert is after the ajax call, you still have to either a: write a callback method to fire when the call completes or, b: complete the ajax call synchronously. See jquery ajax documentation for the async property and its description.

Upvotes: 3

Related Questions