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.