I want to run an ajax request within a function. Basically…
function doIt(id) {
var myVar;
$.ajax({
... url etc...
success: function(result) {
myVar = "Some stuff" + result;
console.log(myVar);
}
})
return myVar;
}
but myvar isn’t set to what it is when I log it after on success. How can I get that variable retuned by the function?
$.ajaxis asynchronous, meaning it doesn’t finish before the next line is executed. What is happening is thatreturn myVar;is being executed before thesuccessevent triggers.Turn the
asyncproperty off and that will superficially fix your problem:However, that will make your browser hang, so the best way to approach this is to put all processing inside of the
successevent.