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

Asked

Viewed 471 times

3

Would have some way when typing the form send the data to the PHP code without having to press the 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>";
        }
    }

?>
  • 1

    There is, but not in the way you probably want. Read about AJAX (even here on the site there is plenty of content)

  • can use the event onchange of the input where the name is entered and go running the code in the php through a call Ajax

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

  • 1

    At a glance here, has this tutorial here which can also help.

1 answer

1


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".

  • Man, that code is too top

  • Vlw! But I made a small change. I don’t think you need that part var form = $("form");

  • There is one more thing missing in the PHP part, you have to take out the variable $EnviarPesq and its reference and the if that catches her, because there is no more button, otherwise it will not work.

  • Well observed. But it was only to have a real idea. : D

  • But what if in the case I after I wrote and decided to pay everything in the input, as I would do to reset the div?

  • can make a else in that if($(this).val()){, guy: }else{ $("#pesquisa").empty(); }

  • It worked, I was already thinking about going through the php kkk, thanks for the explanation!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.