jQuery AJAX Calls - Is it possible to cancel unwanted calls?

Go To StackoverFlow.com


I just wanted to ask. I have text input to allow users to type their city.

jQuery has a keyup event linked to this input and sent an AJAX call after each character change.

I find however many unrequired AJAX calls are sent as the person is typing and depending on the number of results this can slow down performance here.

Is there a way to cancel AJAX calls if a new call is made? Is there a better way to do this?

An example can be seen here: www.datingjapan.co

2012-04-04 21:11
by Adam
Adam, have you imposed a minimum character restriction before calling the function? I think the best practice is to not call something until you want to, as opposed to calling it 50 times and weeding out the 40 you don't want. Or impose a limit of responses on your return data - Blake 2012-04-04 21:12
usually you have 2 controls. One to only start doing ajax after so many characters have been entered (3-4). The other is to send to ajax if nothing has been entered in half a second-one second or so. Otherwise it'll hit the database too much and could slow down user interactio - Rodolfo 2012-04-04 21:21


You can use the abort method of the jqXHR object returned by the ajax method (other AJAX methods like get and post return a jqXHR instance too):

var xhr = $.ajax(opts);

Note that the jqXHR object is effectively just an extension of XMLHttpRequest, and XMLHttpRequest itself also has an abort method.

2012-04-04 21:14
by James Allardice
ok so with jquery I can abort previous calls. Does this mean an abort is sent from the to the server and the operation is cancelled? If I'm sending multiple of the same post request would they all be cancelled or is there a way to identify the one to cancel - Adam 2012-04-04 21:35
@Adam - The abort is sent from the client to the server. Each jqXHR object represents one single request. If you call the abort method of a single instance of jqXHR, that single request is cancelled - James Allardice 2012-04-04 21:39