9
I did a search using ajax
that when clicking a button triggers a request with the term searched and returns with data that fills a combobox html
(select
). So far so good. However, I found it interesting to change this behavior of clicking on the search button, to instead be checked on onkeyup()
during typing.
I happen to feel that there will be an extra charge on the server and I would like to know if you suggest any practice that does not cost so much. Some different technique doing some sort of cache
which I do not know, or instead of searching every keystroke raised, check after a minimum number x of keystrokes be typed (etc).
Another issue: But what if I limit the search to more than 3 characters and then there is some occurrence of exact 3 characters?
Only nay would like:
- That the user always had to click to search and;
- Making too many unnecessary requests.
Ideas?
Follow code below with a brief example of what I’m trying to do:
formulario_search.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>
<link href="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>
busca_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
I could suggest
JQuery autocomplete
, but would evade the scope of the question...– ShutUpMagda
I recommend using a lib to do this, as suggested in the comment above. Regarding a smaller number of requests, I believe it is not possible, since an autocomplete has to respond to any letter provided by the user. If the data is few, you can provide them in the initial request.
– mau humor
You can also add a small delay after the event
keyup
: https://api.jquery.com/delay/ . Just be careful and balance with the response time expectation.– Leonardo Pessoa