Real-time search saving server?

0

Hello, I created a script in jQuery that queries the database, based on what the person typed in a input field. With each key that the user types, the script makes a new request for my API and this is a problem, since I intend to hire a cheap hosting. So I wanted to know how I can improve the following script so I do not have to keep asking the server all the time and spending the resources of the server I want to hire:

$(document).ready(function() {
    $('#input').keyup(function(event) {
        var t = $('#input').val();
        $.getJSON('api', {word: t}, function(json, textStatus) {
            // Em caso de sucesso, essa função será ativa
        });
    });
});
    
asked by anonymous 07.06.2017 / 00:15

1 answer

0

Create a function on click instead of keyup and so the query will only be done when the user finishes typing and clicking a button, or clicking enter to proceed with the search

$(document).ready(function() {
    $('#botao-pesquisar').click(function(){
        var t = $('#input').val();
        $.getJSON('api', {word: t}, function(json, textStatus) {
            // Em caso de sucesso, essa função será ativa
        });
    })
    $('#input').keypress(function(e){
        if(e.which == 13){ // Tecla Enter primida
            $('#botao-pesquisar').click(); // Dispara o evento click no botão de pesquisa
        }
    });
});

It may not be the most perfect way, but it already considerably reduces the constant query on each key press.

    
07.06.2017 / 05:58