How To Abort Ajax Request Using JQuery




Here we consider how to Abort Ajax Request Using JQuery. Lets start with a simple example here. Following are the code for Jquery Ajax Request.

var request = $.ajax({
        type: "POST",
        async: "true",
        url: "WebForm1.aspx/GetData",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
                alert('Success');
        },
        error: function () {
                alert('Something went wrong. Please Try Again');
        }
});



The code behind is as follows.

[WebMethod]
public static void GetData()
{
        // Execute Login Here.
}
});



Now for aborting the Ajax Request we have to use abort() method. That means here we have to use request.abort() after Ajax Request.

request.abort();



var request = $.ajax({
        type: "POST",
        async: "true",
        url: "WebForm1.aspx/GetData",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
                alert('Success');
        },
        error: function () {
                alert('Something went wrong. Please Try Again');
        }
});
request.abort();



But there are some exceptions in this flow of exection.

> If request.abort() execute before sending Request, current HTTP request will get aborted.
> If request.abort() execute after sending Request, then HTTP request complete its task.

But Ajax Success will not get triggered. Instead Ajax Error will get triggered. Please watch the video for demo example. Before starting any ajax call, validate whether the ajax request is null.

var request;
if (request != null){
        request.abort();
        request = null;
}
// Start Ajax Request Here....