Aborting a jQuery Ajax request.

In some cases, you might want to attempt to abort a jQuery Ajax request.

For example:

  1. The user clicks on a button.
  2. The button sends an Ajax request.
  3. The user clicks on the button again, before the Ajax request mentioned in step two has finished.

Obviously, this can be an issue, especially if the user grows impatient and/or has decided to spam the button in question. Thankfully, the jQuery library allows to manually abort an ajax request, which can help you to avoid duplicate requests. Code example:

//Contains the last jqXHR object.
var currentRequest;

//This fictional functional is called whenever our button is clicked.
function buttonClicked(){
    if(currentRequest){
        currentRequest.abort();
    }
    currentRequest = $.ajax({
        url: "/example.php",
        type: "post",
        data: {'test': 'example'}
    });
}

As you can see, we’ve made use of the the abort() function, which can be called on the jqXHR object.

It is important to note that the abort function will not always prevent the request from reaching the server. i.e. If the request reaches the server before abort() is called, the server may continue to process the request. To guard against duplicate Ajax requests, you should disable the element that is used to call it.

Example:

  1. User clicks on a button.
  2. Said button is disabled so that it can no longer be clicked on.
  3. The Ajax request is sent.
  4. The button is re-enabled once the Ajax request has been completed.