How to abort the AJAX requests using JQuery
Overview
We may use the abort() method to cancel a sent AJAX request.
Syntax
XMLHttpRequest.abort()
Syntax of abort method
Parameters
This method doesn't take any parameters and doesn't return any value.
Example
The following code demonstrates how to abort an AJAX request using jQuery.
Explanation
In the above JS code:
Lines 2–7: We use the
ajaxmethod to sent an AJAX request to this URL using the jQuery. Once the request is completed, thesuccesscallback function will be executed.Lines 9–17: We send another AJAX request for the same URL using the
ajaxmethod and assign the AJAX request reference to a variable with the nameXHRToBeAborted.Line 21: We use the
abort()method of theXHRToBeAbortedvariable. This will abort the send request and execute theerrorcallback. Inside the error callback, we print the error message.