Submit when typing in the input type text for the php code on the same page

3

Would you have some form of typing in the form sending the data to the PHP code without having to press submit simply by typing in the text input?

<form method="POST" action="">
  <label>nome: </label>
  <input type="text" name="Pesq" placeholder="Digite o nome"><br><br>
  <input name="EnviarPesq" type="submit" value="Pesquisar">
</form>

<?php

    $EnviarPesq = filter_input(INPUT_POST, 'EnviarPesq', FILTER_SANITIZE_STRING);
    if($EnviarPesq){
        $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>";
        }
    }

?>
    
asked by anonymous 07.06.2018 / 20:35

1 answer

1

You can use a oninput event in the field and call Ajax as you type in the field. But I would suggest including Ajax in a setTimeout function with a short interval (in my example I put 1000 milliseconds = 1 second ), breathe "before submitting a new request.

I also included two lines to abort the last Ajax request and to delete setTimeout while typing quickly:

if(AJAX) AJAX.abort();
clearTimeout(delay);

This is interesting because it cancels the 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 explanation code):

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
   }
});

What about PHP?

I suggest creating your own PHP for this (say, pesquisa.php ) and put only the code that does the search and return in that file (of course, also including the code that connects 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>";
        }
?>
  

Do not forget to include the page in action pain form. Ex: action="pesquisa.php" .

    
07.06.2018 / 23:44