Optimize Ajax Search that Shows Slowness

Asked

Viewed 323 times

3

I have a problem of slowness in this research in ajax.

<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, from the 1st.

I would like her to start searching after the 4th character typed. How can I change my code to make this happen?

3 answers

4


You can check through 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: https://jsfiddle.net/gquwvffk/

  • Exactly that friend. Thank you very much.

2

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

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

    }

I hope I helped. Hugs.

  • It worked too. Thanks friend. It helped a lot, hug.

1

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

  • uses a debauchery or Throttle
  • caches elements you need to use many times.

If you use a function mock the ajax waits a few milliseconds more before making each ajax request. Instead of making a request by keystroke, it waits for the last key and then makes the request. How we are making very small time intervals the user is not affected.

Caching for example $('#resultado') makes you not need to go to the DOM too often to know what that element is.

Your code could then 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
})();
  • 1

    Very good guy. Thanks a lot. Hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.