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. :/
It is probably because you are forgetting AJAX is asynchronous. The
sourcevariable will beundefineduntil thesuccesscallback is completed.Doing
alert(source)beneath that code (outside of the$.ajax()) is almost guaranteed to beundefined.