Tuesday, 19 September 2017

php - Cancel in-flight AJAX requests using Jquery .ajax?











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


Answer



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);
}
});
}

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...