(Didn’t mean to create a new question, but revised the old one enough that the answers don’t make sense, and now there’s a new problem)
I’m a total noob when it comes to jQuery but I am trying to learn. What in tarnation am I doing wrong here?
function MakeCall(url) {
var result;
$.ajax({
url: url,
dataType: "text",
success: function(txt) {
result = txt;
alert(result);
return;
}
});
alert(result);
return result;
}
my problem is that the first alert returns the correct value, but the second alert is returning “undefined” and it pops up BEFORE the first alert, even though the result is getting set properly in the success function… sigh… what am I doing wrong? 🙁
Thanks so much…
Jquery’s ajax functions are asynchronous – therefore the success function will be called after the second alert is run. It will then return from the function before the ajax method is completed.
If you really want to build the app this way, you can add an async option to the call, setting it to false. (http://docs.jquery.com/Ajax/jQuery.ajax#options, see the first entry.) This will result in the success function being called before the $.ajax method returns.
However, doing blocking ajax calls is not recommended, as it will hang the script and the browser.
Therefore, I advise you to restructure the application as such: