Open In App

How to cancel the current request in Ajax ?

Improve
Improve
Like Article
Like
Save
Share
Report

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>
 
<head>
    <meta name="viewport"
          content="width=device-width,
                         initial-scale=1.0" />
    <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">
            If request successful than 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>
 
    <script>
        var head = document.getElementById("text");
        var request = new XMLHttpRequest();
        function requestData() {
            request.onload = function () {
                head.innerHTML = this.responseText;
            };
            request.open("GET", "https://...com", true);
            request.send();
        }
        function abortRequest() {
            head.innerHTML =
                request.abort() +
                "<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=
    </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.

 



Last Updated : 14 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads