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