How to avoid the overhead of a continuous ajax request for a keyup event?

eg. In the search form, when the user enters some text, at this time the AJAX request should send a keyup for each keyup event with the search key in the form of a query string. The search key will be the value from the input field.

If the user enters "ABCD", in this case 3 AJAX requests must first be killed / canceled, because in the fourth AJAX search request there will be "ABCD"

$(document).ready(function(){ $("#searchInput").keyup(function(){ ajaxSearch( $("#searchInput").val() ); }); }); 

In the keyup event, I call the following function "ajaxSearch ()".

 function ajaxSearch(searchKey) { $.ajax({ type: "get", url: "http://example.com/ajaxRequestHandler/", data: "action=search&searchkey=" + searchKey }).done(function() { /* process response */ }); } 
+5
source share
2 answers
 var request; function ajaxSearch(searchKey) { /* if request is in-process, kill it */ if(request) { request.abort(); }; request = $.ajax({ type: "get", url: "http://example.com/ajaxRequestHandler/", data: "action=search&searchkey=" + searchKey }).done(function() { /* process response */ /* response received, reset variable */ request = null; }); } 
+5
source

With Atul Bhosale's answer, there are four more requests when the user types “ABCD”. It is only about a set of server speed and response time.

Better to use a timeout. In this case, the request is simply sent if the user "completes / takes a timeout":

 $("#searchInput").keyup(function(){ var value = $(this).val(); setTimeout( function() { ajaxSearch(value) }, 300 ); }); 

Just play with the timeout. For me, 300 ms is good ...

0
source

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


All Articles