I have a script that does an ajax request out on a keyup event on my search input box. I am noticing in Firefox (I am looking at the console) that every request that is sent off finishes. So there are a ton of ajax requests that happen.
Is there anyway to kill an ajax request in progress upon a keyup event?
jQuery:
jQuery(function() {
var request;
request = function(url, keyword) {
return $.post('/backpack/' + url + '/search?keyword=' + keyword, function(data) {
var el;
el = "#result_" + url;
return $(el).html(data);
});
};
$("#search_text").bind("keyup", function() {
var query, url, _i, _len, _ref;
query = $(this).val();
if (query.length > 2) {
_ref = ['tracks', 'albums', 'artists'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
url = _ref[_i];
request(url, query);
}
return $("#search_suggestions").show();
} else {
return $("#search_suggestions").hide();
}
});
return $("#suggestion_all_results").bind("click", function() {
return $('#search_form form').submit();
});
});
To abort a previous Ajax request on a new request with jQuery, we can call the abort method on the request object. For instance, we can write: const currentRequest = $. ajax({ type: 'GET', url: 'https://yesno.wtf/api', }) $.
Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort() . See the documentation: abort Method (MSDN). Cancels the current HTTP request.
This has already been answered in the ultimate-uber-authoritative thread here.
Short answer: it returns an XHR object and you can call abort()
If you are sending on keyup events, you might also think about adding a delay; it's going to be a pretty big load on your server, so wait for a pause of a few seconds between strokes before you bother kicking off the event.
As Erv Walter said in the above thread's comments: "Of note, if the server has already received the request, it may continue processing the request (depending on the platform of the server) even though the browser is no longer listening for a response. There is no reliable way to make the web server stop in its tracks with processing a request that is in progress."
I've run into the same issues doing ajax suggest lookups ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With