JQuery Keyup Ajax Request: Kill Previous Requests

I have a script that executes an ajax request in a keyup event in an input field for a search. I notice in Firefox (I look at the console) that every request sent ends. So there is a ton of ajax requests that occur.

Is there anyway to kill the ajax request on 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(); }); }); 
+4
source share
2 answers

This has already been said in the ultimately uber-authoritative stream .

Short answer: it returns an XHR object and you can call abort()

If you send events from the keyboard, you might also consider adding a delay; this will be a pretty heavy load on your server, so wait a few seconds between the strokes before you start with this event.

As Erv Walter said in the aforementioned stream comments: β€œIt should be noted that if the server has already received the request, it can continue to process the request (depending on the server platform), although the browser no longer listens for the response. There is no reliable way to make the web server stop on its own tracks when processing the requested request. "

I ran into the same problems that ajax offering search do;)

+4
source

You just need to save the return value of each request you send, and before adding a new one, first run savedRequest.abort() .

0
source

Source: https://habr.com/ru/post/1380472/


All Articles