1
In a search input, an ajax request is made at each letter pressed through a Keypress in the field, but at each key pressed a new request is made, ie if the user type fast, and he type a value of 10 letters, 10 different requests will be made, and the same 10 will be processed and sent back by my PHP, and this may cause me some confusion in the return of this data to the user if a previous request is processed late, so I want every keystroke pressed, previous requests are aborted and then send the new request.
$(document).on("keypress", ".meuInput", function(){
var val = $(this).val();
if(val != ''){
jQuery.ajax({
type: "POST",
url: "meuarquivo.php",
datatype: "json",
data: {src: val},
success: function(data)
{
//processa retorno
}
});
});
The third option, with delay in the request has no need to abort the requests?
– Leo Letto
@Leoletto the delay serves to prevent AJAX requests being made while the user is still typing, in the example above the AJAX request will be made 2 seconds after the user finishes typing.
– Tobias Mesquita
If I reduce this delay to 500, would I lose some performance? Because 2 seconds I found it a little big
– Leo Letto
@Leoletto does not exist an ideal value, just remember that small interruptions are normal while you type, so 0.5s can be a short time for some users, so the ideal is to seek a good balance point
– Tobias Mesquita
I think I will opt for the second option and post each letter typed, and interrupt it, gives an impression of a faster return and solves the problem of excessive requests, Thanks for the help
– Leo Letto
@Leoletto I think it doesn’t solve, you know, make a
.abort()
does not mean that the request on the server side will be stopped, if it has already been delivered, PHP will do all its work, but the browser will ignore the return.– Tobias Mesquita
an option to relieve the server side, is to set a minimum size to search, type 3 letters, with a range of 0.5s and at least 3 characters, I believe will have a good performance relationship with user experience.
– Tobias Mesquita
The problem of limiting the characters is that the values to be searched can vary understand? If the user wants for example to search all the results with the letter A and I limit the search 2 or more characters he will not have access to the results by letter, this solution is more for people with slower internet
– Leo Letto
I tested on connections 5mb above, requests are sent and processed in the order they were typed, but below that some new ones are sent before the previous ones, causing a bug in the view
– Leo Letto