Open In App

How to cancel XMLHttpRequest in AJAX ?

Last Updated : 14 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 server.

XMLHttpRequest.abort() Method: This method is used to abort or cancel the HTTP request. It will change the readyState of the request to 0, which means the state is not being initialized and the request will not be processed further.

Syntax:

var request = new XMLHttpRequest();
request.abort();

Note: The abort() method will not accept any argument or parameter, but it will return undefined when the request has aborted any value.

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
        content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
  
    <style>
        #container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
        }
  
        #btnDiv {
            width: 20vw;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-around;
        }
  
        .btn {
            cursor: pointer;
        }
    </style>
</head>
  
<body>
    <div id="container">
        <h2 id="heading" style="color:green;">
            GeeksforGeeks
        </h2>
          
        <div id="btnDiv">
            <button class="btn" onclick="requestData()">
                Request Data
            </button>
            <button class="btn" onclick="abortRequest()">
                Abort Request
            </button>
        </div>
    </div>
  
    <script>
        var head = document.getElementById('heading');
        var request = new XMLHttpRequest();
        function requestData() {
            request.onload = function () {
                head.innerHTML = this.responseText;
            }
            request.open('GET', 'gfgInfo.txt', true);
            request.send();
        }
        function abortRequest() {
            head.innerHTML = request.abort() +
                "<br>It shows undefined, as the data"
                + " is lost on aborting request.";
        }
    </script>
</body>
  
</html>


Output:

 

Browser Support:

  • Chrome
  • Firefox
  • Opera
  • Safari
  • Edge
  • Internet Explorer


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads