I made a search using ajax
that when clicking a button triggers a request with the searched term and returns with data that fills combobox html
( select
). So far so good. However, I found it interesting to change this behavior from clicking the fetch button to, instead, being checked in onkeyup()
while typing.
I happen to feel that there will be an extra load on the server and I wonder if you suggest some practice that does not cost so much. Some different technique doing some sort of cache
that I do not know, or instead of doing search every keystroke raised, check after a minimum number of keys x being typed (etc).
Another question: But what if I limit the search to more than 3 characters and then there is an occurrence of an exact 3 characters?
Just not wanted:
Ideas?
Follow the code below with a brief example of what I'm trying to do:
form_bus.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script><linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <!-- Css do Bootstrap opcional, só coloquei pra carregar um estilinho básico e mostrar o íconezinho da lupa -->
<script>
$(document).ready(function()
{
$('#termo_busca').keyup(function()
{
$.ajax({
type: 'POST',
url: 'busca_ajax.php',
data: {
nome: $("#termo_busca").val()
},
success: function(data)
{
$('#listafornecedores').html(data);
}
});
});
});
</script>
<style>
body { font-size:14pt; padding:5%; }
#listafornecedores { width:500px; }
</style>
</head>
<body>
Nome fornecedor: <input type="text" id="termo_busca" name="termo_busca">
<button id="btn_busca">
Procurar <span class='glyphicon glyphicon-search'></span>
</button>
<br><br>
<form action="" method="post">
<b>Fornecedores encontrados com o termo pesquisado:</b><br>
<select id="listafornecedores" onclick="if( $('#listafornecedores').html() == '' ){ alert('Sem resultados carregados.\n Faça uma busca digitando o nome de um fornecedor.');}"></select>
<br>
... outros campos ...
<br>
<input type="submit" name="submit" value="Salvar">
</form>
</body>
<html>
search_ajax.php
<?php
/*
--Tabela fornecedores usada para teste:
CREATE TABLE 'fornecedores' (
'id' int(11) NOT NULL,
'nome' varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
ALTER TABLE 'fornecedores'
ADD PRIMARY KEY ('id'),
ADD KEY 'idx_fornecedor_nome' ('nome');
ALTER TABLE 'fornecedores'
MODIFY 'id' int(11) NOT NULL AUTO_INCREMENT;
--Massa de testes: fornecedores disponíveis para busca
INSERT INTO 'fornecedores' ('nome') VALUES ('Samsung'),('Microsoft'), ('Apple'),('Fornecedor Homônimo RJ'),('Fornecedor Homônimo SP'),('Fornecedor Homônimo MG');
*/
//MySQLi DESENVOLVIMENTO
$db_host="localhost";
$db_port="5432";
$db_name="testdb";
$db_user="root";
$db_password="";
$dbcon = mysqli_connect( $db_host, $db_user, $db_password );
mysqli_select_db($dbcon,$db_name);
mysqli_query($dbcon,"SET NAMES 'utf8'");
$nome = mysqli_real_escape_string($dbcon,$_POST["nome"]);
// se enviar nome vazio, não carregar nada
if(trim($nome)==''){ die(); }
$query = "SELECT * FROM fornecedores WHERE nome like '$nome%'";
$result = mysqli_query($dbcon,$query);
$options='';
while($linha = mysqli_fetch_assoc($result))
{
$options.='<option value="'.$linha["id"].'">'.$linha["nome"].'</option>';
}
echo $options; // isto voltará na variável data do ajax