Depending on how I write an ajax request, I get different results. Below, is a version I have written that works as intended:
$('btn').click(function(){
$.ajax({
url: "JSONHandler.aspx",
type: 'get',
data: { IsParam : true, anotherParam: paramString, lastParam: paramString2 }, // this data is arbitrary
cache: false,
error: function () {
alert("You made an error");
},
dataType: 'json',
success: function (data) {
if (data.result == false) {
$.ajax({
url: "JSONHandler.aspx",
type: 'get',
data: {IsNewParam : true, anotherNewParam: paramNewString}, // this data is arbitrary
cache: false,
error: function () {
alert("You made a different error");
},
dataType: 'json',
success: function (data) {
if (data.result == true) {
// do stuff
} else {
// do other stuff
}
}
});
}
else {
// Do different things
}
}
});
}
However, if I write the code like this, the function does not preform as inteneded:
$('btn').click(function(){
$.ajax({
url: "JSONHandler.aspx",
type: 'get',
data: { IsParam : true, anotherParam: paramString, lastParam: paramString2 }, // this data is arbitrary
cache: false,
error: function () {
alert("You made an error");
},
dataType: 'json',
success: function (data) {
if (data.result == false) {
var result = callAjax();
if (result == true)
// do stuff
else
// do other stuff
}
else {
// Do different things
}
}
});
}
function callAjax()
{
$.ajax({
url: "JSONHandler.aspx",
type: 'get',
data: {IsNewParam : true, anotherNewParam: paramNewString}, // this data is arbitrary
cache: false,
error: function () {
alert("You made a different error");
},
dataType: 'json',
success: function (data) {
if (data.result == true) {
return true;
} else {
return false;
}
}
});
}
For example, let say I want the top ($('btn').click) function to throw an alert in the "// do stuff" part. If I run it through the first example, I get my alert as intended.
However if I put the alert in the "// do stuff" in the second example, I do not get the alert as intended.
Looking through the dev tools in the browser, I can see the second function being calls and returned as intended, however by the time this happens, the original (calling) ajax function has already moved past the branching if (result == true) statement and does not take that result into account, whether it is true or not.
Why is this? I imagine it has to do with the async part of ajax, but I guess I just don't see why the top example would work but the bottom does not.
Could someone help me understand?
The first Ajax call doesn't wait in your second example.It calls the second Ajax call and immediately goes to result == true
which is undefined. You should pass your stuff as callback to the second ajax call and call it in success
.
Like
var result = callAjax(function (result) {
if (result == true)
// do stuff
else
// do other stuff
});
And in callAjax()
function callAjax(callback) {
...
success: function (data) {
callback(data.result);
}
}