AJAX HTTP Requests Cancellation

AJAX HTTP Requests Cancellation

Reading Time: 5 minutes

Sometimes when we call the server to perform some action as a response to an AJAX request, we want to discard this request because of particular reason. For example I had to perform a render action for a request with some parameters and send back as a response rendered template in HTML markup. This cancellation should help us dealing with unnecessary responses from server as well as avoiding redundant network traffic and unsynchronized UI when.

Scenario

Alice fills a form on the client side, for example name and phone and gets back from the server the fancy decorated rendered html to the browser.

Request:

We obviously don’t want to create a request for each character filled in the form so we create some sort of a debounce function to help us reduce the HTTP requests. But we can do even more. Suppose that we have a debounce function of 2 seconds, and Alice filled her name in the name field, waited for 2 seconds that started to fill the phone field. Obviously a new request will be fired to the server while the older request is still live, but we don’t need the older one because it is now not synchronized with the UI. We need a way to cancel the old request and to treat only the latest request.

Naive Code And Example

here I created a little demo of the situation with the debounce function and a function to mock the AJAX task. Of course it is not the best code you will ever see and uses jQuery and blah blah but that clears the point. If you notice and sharp enough you can make a render request and while the request is being processed you can create another request for render.

1

Abort To The Rescue

The JavaScript xhr function (which I believe is still being used by most of the libraries/frameworks, for example vueResource and the before parameter where you would cancel the xhr request) comes with an option to abort it self. The only addition to the code above is single condition which can help your application reduce requests even more (with the debounce function)