Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel in-flight AJAX requests using Jquery .ajax? [duplicate]

Possible Duplicate:
Kill Ajax requests using JavaScript using jQuery

Here is the simple code I am working with:

$("#friend_search").keyup(function() {      if($(this).val().length > 0) {         obtainFriendlist($(this).val());     } else {         obtainFriendlist("");     }  });  function obtainFriendlist(strseg) {      $.ajax({        type: "GET",        url: "getFriendlist.php",        data: "search="+strseg,        success: function(msg){         UIDisplayFriends(msg);        }      }); } 

Essentially, if a keyup event is fired before the function obtainFriendlist returns a result (and triggers UIDisplayFriends(msg), I need to cancel the in-flight request. The issue I have been having is that they build up, and then suddenly the function UIDisplayFriends is fired repeatedly.

Thank you very much, and advice is helpful too

like image 593
TaylorMac Avatar asked Nov 05 '11 22:11

TaylorMac


1 Answers

The return value of $.ajax is an XHR object that you can call actions on. To abort the function you would do something like:

var xhr = $.ajax(...) ... xhr.abort() 

It may be smart to add some debouncing as well to ease the load on the server. The following will only send an XHR call only after the user has stopped typing for 100ms.

var delay = 100,     handle = null;  $("#friend_search").keyup(function() {     var that = this;     clearTimeout(handle);     handle = setTimeout(function() {         if($(that).val().length > 0) {             obtainFriendlist($(that).val());         } else {             obtainFriendlist("");         }     }, delay); }); 

A third thing that you should really be doing is filtering the XHR responses based on whether or not the request is still valid:

var lastXHR, lastStrseg;  function obtainFriendlist(strseg) {     // Kill the last XHR request if it still exists.     lastXHR && lastXHR.abort && lastXHR.abort();      lastStrseg = strseg;     lastXHR = $.ajax({        type: "GET",        url: "getFriendlist.php",        data: "search="+strseg,        success: function(msg){          // Only display friends if the search is the last search.         if(lastStrseg == strseg)            UIDisplayFriends(msg);        }      }); } 
like image 80
Brian Nickel Avatar answered Sep 30 '22 18:09

Brian Nickel