Problem with onkeyup in input

1

I did a little JavaScript function to do a dynamic search in the database without giving refresh and it is working, but I think there is a problem with onkeyup . When entering text in the input field and then deleting this text, div#resultado shows all the fields registered in the database (which will not be legal). Is there another method of removing this bug from empty field?

var req;

// FUNÇÃO PARA BUSCA LOJA
function buscarLojas(valor) {

  // Verificando Browser
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }

  // Arquivo PHP juntamente com o valor digitado no campo (método GET)
  var url = "busca.php?valor=" + valor;

  // Chamada do método open para processar a requisição
  req.open("Get", url, true);

  // Quando o objeto recebe o retorno, chamamos a seguinte função;
  req.onreadystatechange = function() {

    // Exibe a mensagem "Buscando lojas..." enquanto carrega
    if (req.readyState == 1) {
      document.getElementById('resultado').innerHTML = 'Buscando lojas...';
    }

    // Verifica se o Ajax realizou todas as operações corretamente
    if (req.readyState == 4 && req.status == 200) {

      // Resposta retornada pelo busca.php
      var resposta = req.responseText;

      // Abaixo colocamos a(s) resposta(s) na div resultado

      document.getElementById('resultado').innerHTML = resposta;

    }
  }
  req.send(null);
}

HTML code:

<div class="search-box">
  <input type="text" name="busca" id="busca" placeholder="Buscar lojas" onkeyup="buscarLojas(this.value)">
  <span></span>

  <div id="resultado"></div>
</div>
    
asked by anonymous 08.07.2017 / 15:13

3 answers

1

I followed the hint of putting a condition, but it did not work with return false, I got passed null to div#resultado . For those of you with the same problem, follow the code:

else{
                document.getElementById('resultado').innerHTML = null;
            }
    
08.07.2017 / 20:40
2

Test the number of characters the field has before ordering the data, only when it has at least 1 character written:

// FUNÇÃO PARA BUSCA LOJA
function buscarLojas(valor) {
     if(valor.length == 0){
           return false;
     }
...

You can even do only when you have 2 or 3 characters so that you do not see as many results as possible.

    
08.07.2017 / 15:17
1

The onkeyup calls the function when ANY keypad button is pressed, both backspace and the tab , ie if you delete it it will fetch the written result, like the value written is "" (empty string) if you are using a LIKE it will fetch all results from the database, ie the solution might be on your php server , so before you bring the search results try to validate if there is a value in the search variable.

    
08.07.2017 / 17:55