How to cancel the current request in Ajax ?
Last Updated :
01 Aug, 2024
In this article, we will see how to cancel the current request in Ajax. AJAX (Asynchronous JavaScript and XML) is a technique for creating fast and dynamic web pages. It allows a web page to update its content without reloading the entire page.
An AJAX request is an HTTP request made using JavaScript, usually with the XMLHttpRequest object or the more modern fetch() API, to retrieve data from a server in the background, without disrupting the current state of the page. The data retrieved by an AJAX request can be in various formats, including plain text, HTML, JSON, or XML.
Ajax request cancellation is the process of stopping an ongoing asynchronous HTTP request made with AJAX technology. It can be achieved by using the abort() method of the XHR (XMLHttpRequest) object. The abort() method stops the request and terminates the response. This can be useful in situations where a user initiates a request but then decides to cancel it before it has been completed. For instance, if a user starts a request to search for information, but then changes their mind and decides to search for something else before the first request has been completed, they can cancel the first request and start a new one with the updated information. However, once a request has been completed or has been canceled, its abort() method has no effect.
Syntax:
var xhr = new XMLHttpRequest();
xhr.abort();
Here, the abort() method doesn't accept any arguments, but it will return undefined when the request has aborted any value.
Example 1: In this example, we are sending a request to an example API. If we don't cancel the request then API will fetch the data, & if we click the abort request button, then the request will be canceled. Here, we are using some random URL to generate random data.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Cancel the Current Request in Ajax</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f7f7f7;
font-family: Arial, sans-serif;
margin: 0;
}
.container {
background: #fff;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
max-width: 600px;
width: 100%;
}
h1 {
color: #28a745;
margin-bottom: 1rem;
font-size: 2rem;
font-weight: 700;
}
h3 {
color: #333;
margin-bottom: 2rem;
font-size: 1.2rem;
}
.btnDiv {
margin-top: 1rem;
}
.btn {
background-color: #007bff;
color: #fff;
border: none;
padding: 0.75rem 1.5rem;
font-size: 1rem;
font-weight: 600;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s, box-shadow 0.3s;
margin: 0 0.5rem;
}
.btn:hover {
background-color: #0056b3;
}
.btn:active {
background-color: #004494;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
}
.response {
margin-top: 2rem;
font-size: 1rem;
color: #555;
}
</style>
</head>
<body>
<div class="container">
<h1>Geeksforgeeks</h1>
<h3>If request successful then data will be displayed, else undefined.</h3>
<div class="btnDiv">
<button class="btn" onclick="requestData()">Request Data</button>
<button class="btn" onclick="abortRequest()">Abort Request</button>
</div>
<div id="response" class="response"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var request;
function requestData() {
if (request) {
request.abort(); // Abort any ongoing request
}
request = $.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1", // Example URL
method: "GET",
success: function(data) {
$("#response").html("Data received: <br>" + JSON.stringify(data));
},
error: function() {
$("#response").html("Error occurred");
}
});
}
function abortRequest() {
if (request) {
request.abort();
$("#response").html("Request aborted.<br>Undefined as data is lost due to abort");
}
}
</script>
</body>
</html>
Output:
From the output, the first time we request data, we get the data successfully. But the second time before the request is completed, we click the abort request button and the request is aborted before it is completed.
Example 2: This example uses a jquery ajax request to show how to cancel the request. Here also, we are using some random URL to generate random data.
HTML
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
content="width=device-width,
initial-scale=1.0" />
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
<style>
.container {
text-align: center;
}
.btn {
cursor: pointer;
padding: 1rem;
background-color: rgb(234, 234, 72);
color: rgb(86, 5, 5);
}
.btn:active {
background-color: rgb(139, 139, 10);
}
</style>
</head>
<body>
<div class="container">
<h1 id="header"
style="color: green">
Geeksforgeeks
</h1>
<h3 id="text">
The request will automatically aborted
as soon as we click request data
button.
</h3>
<div class="btnDiv">
<button class="btn"
onclick="onRequest()">
Request Data
</button>
</div>
</div>
<script>
var head = document.getElementById("text");
var xhr;
function onRequest() {
//Requesting the data from api
xhr = requestData();
//aborting the request after requesting
abortRequest(xhr);
}
function requestData() {
var xhr = $.ajax({
type: "GET",
url: "https://...com",
});
return xhr;
}
function abortRequest(xhr) {
head.innerHTML =
"<br>Undefined as data is lost due to abort";
}
</script>
</body>
</html>
Output: The below output shows how the requested API is canceled using the abort() method.
Similar Reads
How to cancel XMLHttpRequest in AJAX ?
In this article, we will learn how can we stop or cancel the already sent HTTP request to the server. XMLHttpRequest is an object that we use to send an HTTP request to the server to get the required data from the server. XMLHttpRequest provides an abort() method to cancel the sent request to the se
2 min read
How to cancel an $http request in AngularJS ?
In AngularJS, we use different sources to fetch the data as per our needs. We call different data source APIs using $http requests. We can fetch the data along with cancelling the real-time running request. In AngularJS, we can use the $q service along with the promises to cancel the request. Also,
4 min read
What is an asynchronous request in AJAX ?
In this article, we will have a deep look into Asynchronous AJAX requests. Basically, AJAX provides two types of requests namely Synchronous AJAX and Asynchronous AJAX. Asynchronous requests in AJAX don't wait for a response from the server whereas synchronous waits for the response. When asynchrono
3 min read
How to send a PUT/DELETE request in jQuery ?
To send PUT/DELETE requests in jQuery, use the .ajax() method, specifying the type as PUT or DELETE. This enables updating or deleting server resources via AJAX. Unlike .get() and .post(), jQuery lacks dedicated .put() and .delete() methods.ApproachTo make a PUT or DELETE requests in jQuery we can u
2 min read
How to Detect AJAX Request to Normal Request in Node.js ?
When developing web applications with Node.js, you often need to differentiate between AJAX (Asynchronous JavaScript and XML) requests and normal HTTP requests. AJAX requests are typically used to fetch data without reloading the entire page, while normal requests often result in full page loads. De
3 min read
Explain the role of callback function in AJAX
AJAX (Asynchronous Javascript and XML) is used to create web applications asynchronous. It uses XMLHttpRequest to transport data to and from the server. AJAX always works on Request and Response means AJAX will Request anything from the server and the server will give the Response back to AJAX. We h
3 min read
How to use an HTTP GET or POST for Ajax Calls?
Sending an HTTP request to the server using AJAX is the most common way of fetching data these days. It provides us with methods to send and receive data. In this article, we are going to discuss GET and POST methods.GET method: This method is used to GET or RECEIVE the data from a file, API, etc.Ho
3 min read
How to prevent the default action of an event in JavaScript ?
The term "default action" usually refers to the default behavior or action that occurs when an event is triggered. Sometimes, it becomes necessary to prevent a default action of an event. Let's create HTML structure with event and function that needs to prevent the default actions. HTML <!DOCTYPE
3 min read
How to get server response from an AJAX request using jQuery ?
In this article, we will see how we can use jQuery to get the server response to an AJAX request. The jQuery ajax() method implements the basic Ajax functionality in jQuery. It communicates with the server via asynchronous HTTP requests. Syntax:$.ajax(url);$.ajax(url,[options]);Parameters:url: A URL
4 min read
How to make ajax call from JavaScript ?
Making an Ajax call from JavaScript means sending an asynchronous request to a server to fetch or send data without reloading the web page. This allows dynamic content updates, enhancing user experience by making the web application more interactive and responsive.In this article, we'll learn about
4 min read