sdhakal sdhakal - 6 months ago 27
jQuery Question

Call a function before ajax Success or Failure

I am using $.ajax to make a post request. Then, I am trying to call a function before success or failure of the ajax request. Right now my approach is like following

var someCallback = function() {
//do something
};
var Success = false;
$.ajax({
type: "POST",
url: "/some/service",
dataType: "text",
data: JSON.stringify(someData),
contentType: "application/json; charset=utf-8",
success: function (data) {
someCallBack(); //<--- this is the function
Success = true;//doesnt goes here
},
error: function (textStatus, errorThrown) {
someCallBack();
Success = false;//doesnt goes here
}

});


The thing is, i need to run someCallBack() after the ajax request completes irrespective of whether it succeeds or fails but before success or error callback is called. I dont want to use ajaxStart and ajaxStop in this scenario. I looked at 'complete' callback, but it is only called after error or success. I don't want to call the someCallBack() at two places. Any Suggestions, Please.

Answer

I think you're looking for ajax' deferred interface, which has an always method. And you can chain your success/error handlers after that - though you cannot use those that go into the options object.

$.ajax({
    type: "POST",
    url: "/some/service",
    dataType: "text",
    data: JSON.stringify(someData),
    contentType: "application/json; charset=utf-8"
})
.always(someCallBack)
.done(function (data) {
    var Success = true; // goes here after someCallBack()
})
.fail(function (textStatus, errorThrown) {
    var Success = false; // goes here after someCallBack()
});
Comments