How To Abort A Previous Ajax Request In jQuery

Overview

When using ajax to request a page or data, there will be occasions where you will need to cancel the ajax call. I found this useful after building a search as you type feature and I would abort the previous search and request a new ajax search each time they typed a new letter. Since their old word has changed to a new meaning, completing the old request is meaningless since the new word is an entirely different category. For example the typed fee and then they type `d` making the word feed. So I would abort a previous ajax request in jquery and issue a new ajax search on feed.

Additional uses for aborting an ajax request in jquery

Another reason may be that the page you are calling enters an infinite loop and stops the call from returning. Maybe you need to cancel a previous request before making a new request to prevent duplicate requests from being sent.

How To Abort A Previous Ajax Request In jQuery

Luckily jQuery has made this almost too easy as you can see by my example below.

/* our handler to the ajax request */
var xhr = null;

function goAjax()
{
	/* if there is a previous ajax request, then we abort it and then set xhr to null */
	if( xhr != null ) {
		xhr.abort();
		xhr = null;
	}

	/* and now we can safely make another ajax request since the previous one is aborted */
	xhr = $.ajax({
		type: "POST",
		url: "/some/url",
		data: "variables=whatever&var2=something",
		success: function(msg) {
			/* handle the ajax response */
		}
	});
}

Now you can call the goAjax() function as often as you like and it will cancel the previous ajax request if it hasn’t been completed before making a new request preventing duplicate requests from stacking up.

<a href='javascript:goAjax();'>Click me as much as you like</a>

And that is all there is to it. Simple and straightforward.