Setup:
I am doing an ajax-jsonp call, which is working fine. The callback function of this changes value of a variable, “myVaraible”. Just after the call, there is some if-else logic which works on the value of “myVaraible”.
Here is the code:
<script>
function myfunction() {
$.ajax({
url: myURL,
dataType: "jsonp",
jsonp : "jsonp",
async: false,
jsonpCallback: "jsonpCallbackFn"
});
}
function jsonpCallbackFn(mydata) {
alert("inside jsonpCallbackFn");
if(something) {
// change value of a variable "myVariable";
}
}
$(document).ready(function() {
$("#preview_button").mouseover(function() {
myfunction();
alert("after myfunction");
// do some if-else logic based upon the value of myVariable which is updated by the call to myfunction()
});
});
</script>
The Problem:
The ajax call remains ‘pending’, the control moves to the if-else block (effectively executing on the old/stale value of myVariable). And then the ajax call completes. In short, out of the 2 alert boxes, alert("after myfunction"); executes first and then alert("inside jsonpCallbackFn");
As you can see, I have already set async: false,, but looks like that is not working as expected. Can anyone tell me what am I doing wrong? Also, I am not sure if I have explained the entire scenario properly, please let me know if any more info is needed.
Thanks a lot.
From the $.ajax documentation:
So, you’ll need to put anything that relies on the results of the request in the callback.