How to Cancel AJAX Request in JavaScript
In web development, making asynchronous requests using AJAX is a common practice to fetch data from a server without reloading the entire page.
However, there are situations where you might need to cancel or abort these requests. Let’s see few of them:
Why need to cancel an AJAX request
There are several scenarios in which you might need to abort an AJAX request:
-
User Navigation: When a user navigates away from a page or cancels an action, you may want to abort pending AJAX requests to avoid unnecessary server load or unexpected behavior.
-
Concurrency Control: In situations where you have multiple AJAX requests that depend on each other, you might need to abort or cancel requests when a more recent one is initiated.
-
Performance Optimization: Aborting requests can help improve the performance of your web application by reducing unnecessary network traffic.4
There are different ways to make AJAX requests in JavaScript, so there will be different ways to cancel AJAX request as well. Here we will see ajax cancelation examples for Fetch API, Axios and XMLHttpRequest.
Cancel Fetch API Request:
With the introduction of the Fetch API, a more modern and flexible way to make AJAX requests, you can use the AbortController
and AbortSignal
to abort fetch requests.
Here is an example with fetch-api:
const controller = new AbortController();
const signal = controller.signal;
fetch("https://api.example.com/data", { signal })
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
// Handle the data
})
.catch((error) => {
if (error.name === "AbortError") {
// Handle the request being aborted
} else {
// Handle other errors
}
});
// To abort the request:
controller.abort();
Abort Axios Request:
If you prefer to use a library like Axios for making AJAX requests, You need to do the same thing as the Method 2 (Fetch API) for request cancellation.
Here is an Example:
const controller = new AbortController();
axios
.get("/foo/bar", {
signal: controller.signal,
})
.then(function (response) {
//...
});
// cancel the request
controller.abort();
Ajax cancellation example for XMLHttpRequest
In the past, when XMLHttpRequest
(XHR) was the primary method for making AJAX requests, you could abort a request by using the abort()
method associated with the XHR
object.
Example for XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
// Set a timeout for the request (optional)
xhr.timeout = 5000; // 5 seconds
xhr.onload = function () {
// Handle successful response
};
xhr.onerror = function () {
// Handle errors
};
// Send the request
xhr.send();
// To abort the request:
xhr.abort();
Depending on your project and preferences, you can choose between the classic XMLHttpRequest with the abort() method, and the Axios or modern Fetch API with AbortController.