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

Question:

Would there be any way to type the form sending the data to the PHP code without having to press submit , simply 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>";
        }
    }

?>

Answer:

You can use an oninput event in the field and call Ajax as you type in the field. However, I would suggest including Ajax in a setTimeout function with a small interval (in my example I put 1000 milliseconds = 1 second ), so that it gives Ajax time to "breathe" before sending a new request.

I also added two lines to abort the last Ajax request and clear 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 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
   }
});

What about PHP?

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

Don't forget to include the page in the form action . Ex.: action="pesquisa.php" .

Scroll to Top
AllEscort