0
I made a small Javascript function to make a dynamic search in the database without giving refresh and it’s working, but I think there’s a problem with onkeyup. When inserting text into field input and then delete that text, the div#resultado shows all fields registered in the database (which will not be legal). There is another method to remove this bug 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>