Skip to content
Related Articles
Open in App
Not now

Related Articles

How to cancel XMLHttpRequest in AJAX ?

Improve Article
Save Article
  • Last Updated : 14 May, 2022
Improve Article
Save Article

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.


var request = new XMLHttpRequest();

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



<!DOCTYPE html>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
        #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;
    <div id="container">
        <h2 id="heading" style="color:green;">
        <div id="btnDiv">
            <button class="btn" onclick="requestData()">
                Request Data
            <button class="btn" onclick="abortRequest()">
                Abort Request
        var head = document.getElementById('heading');
        var request = new XMLHttpRequest();
        function requestData() {
            request.onload = function () {
                head.innerHTML = this.responseText;
  'GET', 'gfgInfo.txt', true);
        function abortRequest() {
            head.innerHTML = request.abort() +
                "<br>It shows undefined, as the data"
                + " is lost on aborting request.";



Browser Support:

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!