How to abort an Ajax request using jQuery.

In this guide, we are going to show you how to abort an Ajax request using jQuery.

This can be useful if you need to cancel the request because the user has clicked on a different option. That, or they have pressed the same button twice.

Thankfully, it is pretty easy to abort such requests.

Take a look at the following example:

//Contains the last jqXHR object.
var currentRequest = false;

//An example functional that called whenever a button is clicked.
function buttonClicked(){
    //A request is already taking place
    if(currentRequest !== false){
        currentRequest.abort();
    }
    currentRequest = $.ajax({
        url: "/example.php",
        type: "post",
        data: {'test': 'example'},
        success: function(data){
            //request is finished, set currentRequest to false again
            currentRequest = false;
        }
    });
}

In the code above, we store the current request in a JavaScript variable called “currentRequest”.

When the user clicks on the button, our function will check to see if “currentRequest” is FALSE or not.

If it is not FALSE, then we presume that an Ajax request is already running. At that point, we call the XMLHttpRequest.abort() method to cancel it.

When a request finishes, our code overwrites the “currentRequest” variable with a FALSE value. This basically tells our script that there are no “processing” requests.

It is important to note that the abort function will not always prevent the request from reaching the server.

In other words, if it reaches the server before our function calls the abort method, then the server may continue to process it.

To guard against this kind of situation, you can disable the HTML element.

For example:

  1. The user clicks on an HTML button.
  2. Your code disables the button so that it can no longer be clicked on.
  3. The Ajax request runs.
  4. Your code “re-enables” the button when the Ajax request is complete.