You can use an event oninput
in the field and go calling Ajax as you type in the field. However, I would suggest including Ajax in a function setTimeout
with a short interval (in my example I put 1000 milliseconds = 1 second), to give Ajax time to "breathe" before sending a new request.
I also included two lines to abort the last Ajax request and delete the setTimeout
while typing quickly:
if(AJAX) AJAX.abort();
clearTimeout(delay);
This is interesting because it cancels previous requests while typing in the field. This saves the server from excessive requests, because in my view, what matters is the result when the user stops typing for a brief interval.
Create a div
after the form to receive the data coming from Ajax:
<form method="POST" action="">
...
</form>
<div id="pesquisa"></div>
The complete script looks like this (see the code for explanations):
var delay, AJAX; // declaro a variável do temporizador e do Ajax
$("[name='Pesq']").on("input", function(){ // captura digitação no campo
if(AJAX) AJAX.abort(); // cancela o último Ajax, se existir;
clearTimeout(delay); // apago o temporizador, para não criar um em cima do outro
if($(this).val()){ // só chama o Ajax se o campo não estiver vazio
delay = setTimeout(function(){ // redefino o temporizador
console.log("enviando ajax...");
AJAX = $.ajax({
url: $("form").attr('action'),
type: $("form").attr('method'),
data: $("form").serialize(),
success: function(data){
$("#pesquisa").html(data); // altero o conteúdo da div com o resultado
}
});
}, 1000);
}else{
$("#pesquisa").empty(); // esvazia a div caso o campo esteja em branco
}
});
And PHP?
I suggest creating a PHP for this (say, pesquisa.php
) and put only the code that does the search and return in that file (of course, including also the code that makes the connection to the database through the variable $conexao
):
<?php
// inclua aqui a conexão com o BD
$Pesq = filter_input(INPUT_POST, 'Pesq', FILTER_SANITIZE_STRING);
$itens_coletados = "SELECT * FROM tabela WHERE nome LIKE '%$Pesq%'";
$resultado_de_itens = mysqli_query($conexao, $itens_coletados);
while($exibir_itens = mysqli_fetch_assoc($resultado_de_itens)){
echo "id:" . $exibir_itens['id'] . "<br>";
echo "nome" . $exibir_itens['nome'] . "<br>";
echo "<br>";
}
?>
Don’t forget to include the page in action
form pain. Ex.: action="pesquisa.php"
.
There is, but not in the way you probably want. Read about AJAX (even here on the site there is plenty of content)
– Woss
can use the event
onchange
of the input where the name is entered and go running the code in thephp
through a callAjax
– Ricardo Pontual
in the case it would look something like this then: $.ajax({ url: $(this). attr('action'), type: $(this). attr('method'), date: $(this). serialize(), Success: Function(l) { } });
– João Victor
At a glance here, has this tutorial here which can also help.
– fajuchem