JQuery UI Autocomplete shows answer for earlier text

I use jquery autocomplete. If the user types 2 characters, then he waits, and then enters another. If the first answer comes after the second, it will briefly show the second list, and then display the first list. How can I cancel the first request after the user starts typing more?

$("#city").autocomplete({ source: function( request, response ) { $.ajax({ url: "/geo/json_autocomplete.php", dataType: "json", data: { term: $("#city").val(), countryid: $("#countryid").val() }, success: function( data ) { response( $.map( data, function( item ) { //console.debug(item.value+" "+item.label+" "+item.id); return { label: item.label, value: item.value, id: item.id } })); } }); }, minLength: 2, delay: 500, select: function( event, ui ) { $("#cityid").val(ui.item.id); showForm(); } }); 
+4
source share
1 answer

You can try storing xhr in a variable and compare it with the xhr parameter that you get in the AJAX callback. Call the response function only if they match. You can also adjust the "delay" parameter accordingly.

 var lastXhr; $("#city").autocomplete({ delay: 500, // 500ms between requests. source: function( request, response ) { lastXhr = $.ajax({ url: "/geo/json_autocomplete.php", dataType: "json", data: { term: $("#city").val(), countryid: $("#countryid").val() }, success: function( data, status, xhr ) { if (xhr === lastXhr) { response( $.map( data, function( item ) { //console.debug(item.value+" "+item.label+" "+item.id); return { label: item.label, value: item.value, id: item.id }; })); } } }); }, minLength: 2, delay: 500, select: function( event, ui ) { $("#cityid").val(ui.item.id); showForm(); } }); 
+7
source

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


All Articles