Reputation:
Consider this code example:
var source = null;
$.ajax({
[...],
success:function(data)
{
source = data;
alert(source);
}
});
alert(source);
Now: inside of the success handler, everything is fine, I get the correct data from the webservice and everything is just great. But as soon as JS leaves the $.ajax and is done with it the variable source is null again.
Tell me why. It must be some JavaScript specfic stuff I'm not familiar with. :/
Upvotes: 0
Views: 628
Reputation: 490657
It is probably because you are forgetting AJAX is asynchronous. The source
variable will be undefined
until the success
callback is completed.
Doing alert(source)
beneath that code (outside of the $.ajax()
) is almost guaranteed to be undefined
.
Upvotes: 4
Reputation: 4405
Well, are you sure the success callback is called before the alert outside of the ajax call is triggered?
The ajax call is asynchronous and returns immediately.
Upvotes: 0