Categories
JavaScript Answers

How to Abort a Previous AJAX Request on a New Request with jQuery?

Spread the love

To abort a previous Ajax request on a new request with jQuery, we can call the abort method on the request object.

For instance, we can write:

const currentRequest = $.ajax({
  type: 'GET',
  url: 'https://yesno.wtf/api',
})

$.ajax({
  type: 'GET',
  url: 'https://yesno.wtf/api',
  beforeSend: () => {
    currentRequest.abort();
  },
  success: (data) => {
    // Success
  },
  error: (e) => {
    // Error
  }
});

We create the currentRequest object with the $.ajax method to make the request.

Then in the 2nd ajax call, we call currentRequest.abort in the beforeSend method.

The abort method will cancel the request made in the first ajax call.

We also have the success method that runs when the request is successful.

And the error method runs when there’s an error with the request.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *