Optimize Ajax search that is slow

3

I'm experiencing slowness in this ajax search.

<script type="text/javascript">
    $('#nome').keyup(function () {
        var chars = (this.value);
        $.post('../Ajax/busca_nome', {val: chars}, function (busca) {
            $('#resultado').html(busca);
        });
    });
</script>

It searches the database for each character typed since the 1st.

I would like it to start searching after the 4th character entered. How can I change my code for this to happen?

    
asked by anonymous 20.05.2016 / 19:42

3 answers

4

You can check with string.length .

The function would look like this:

<script type="text/javascript">
    $('#nome').keyup(function () {
        var chars = (this.value);
        if(chars.length > 4){
          $.post('../Ajax/busca_nome', {val: chars}, function (busca) {
             $('#resultado').html(busca);
          });
        }
    });
</script>

Example: link

    
20.05.2016 / 19:51
2

I would think of doing an if before performing the ajax call. Only calling if the value of the field was greater than or equal to 4. Here is the code below:

    if( this.val().length >= 4 ){
       $.post('../Ajax/busca_nome', {val: chars}, function (busca) {
           $('#resultado').html(busca);
       });

    }

I hope I have helped. Hugs.

    
20.05.2016 / 19:54
1

I think there are more improvements you should make than those suggested in the other answers.

If you use a debounce function, ajax waits a few milliseconds longer before making each ajax request. Instead of pressing a key, he waits for the last key and then places the order. Since we are dealing with very small time intervals, the user is not affected.

Caching for example $('#resultado') means you do not need to go to DOM too many times to know what that element is.

Your code could look like this:

(function() { // para não exportar variáveis para o escopo global
    function debounce(fn, delay) { // defenição da função debounce
        var timer = null;
        return function() {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                fn.apply(context, args);
            }, delay);
        };
    }

    var resultado = document.getElementById('resultado'); // colocar o elemento em cache
    var handler = debounce(function() { // criar uma função com debounce
        var chars = this.value;
        if (chars.length < 4) return; // parar aqui se o texto fôr muito curto
        $.post('../Ajax/busca_nome', {
            val: chars
        }, function(busca) {
            resultado.innerHTML = busca;
        });
    }, 400); // 400 ms de espera depois da ultima tecla
    $('#nome').keyup(handler); // passar a super função ao jQuery
})();
    
20.05.2016 / 22:47