I have a standard ajax call from jquery as below.
I would like to check if the json array returned is requesting a new page, and if yes, go there and do not execute the .always callback.
Is there a simple way to do this?
var jqxhr = $.ajax({
url: server_URL + '/index.php',
type: 'post',
dataType: "json",
data: obj
}).done(function (data) {
if (data['go_location']) {
window.location.href = data['go_location'];
} else {
//other stuff
}
}).fail(function () {
alert("ajax error");
}).always(function () {
//other code
});
As name says 'always', .always() is executed in both the case either success or failure. You don't wanna execute .always() on success state but failure state, which is not possible. You are calling three methods namely .done(), .fail(), and .always() on ajax response. All the method are triggered as soon as ajax is complete [.done() and .alway() on success otherwise .fail() and .always()]. We know that jquery/js is asynchronous so, even return statement in any of other method can not stop execution of .always(). In your case only option is don't use .always() method. Either of the state success or failure, either .done() or .fail() is executed. So, you can move your .always() method statements to these methods if needed.
$.ajax({
url: server_URL + '/index.php',
type: 'post',
dataType: "json",
data: obj
}).done(function (data) {
//Do something if ajax succeeds
if (data['go_location']) {
window.location.href = data['go_location'];
} else {
//other stuff
}
}).fail(function () {
//Do something if ajax fails
})