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.

Console
Using abort() function to abort ajax request

Explanation

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.

Free Resources