Onclick to display result

Asked

Viewed 377 times

0

I took a code that when something is typed in the input, it loads the data without refresh on the page, only that I wanted to do it through button, thus avoiding bugs.

I’m not able to convert the code to run with button.

My code . js:

$("#busca").keyup(function(){
    var campo = $("#busca").val();
    $.post('processa.php', {campo: campo},function(data){
    $("#result").html(data);
    });
});

parses.php

$campo = $_POST['campo'];

$result = "SELECT * FROM usuario WHERE nome = '$campo'";
$resultado = mysqli_query($conn, $result);

if($resultado->num_rows != 0 ){
    while($row = mysqli_fetch_assoc($resultado)){
    echo $row('nome');
    echo $row(senha);
    echo $row(data_nasc);
} else { 
    "Nenhum usuário encontrado" 
   }

form:

<form action="processa.php" method="POST">
      <input type="text" class="form-control" name="busca" placeholder="Nome">
      <button id="executar" type="button" class="btn btn-warning"">Buscar</button>
</form>

3 answers

1

The following code must solve:

$("body").on('click', '#executar', function(e) {
    e.preventDefault();
    const campo = $("#busca").val();

    $.post('processa.php', {campo: campo}, function(data) {
       $("#result").html(data);
    });

    return false;
});
  • Didn’t work :/

  • What mistake happened? Maybe it’s not a problem with the method itself. You came to clear the cache after changing (Ctrl + F5), sometimes this can disturb.

1


Just change keyup for click

Description: Link an event handler to the event Javascript "click" or trigger this event in an element. This method is a shortcut .on("click", handler) the first two variations and .trigger("click") in the third. The click event is sent to an element when the mouse pointer is over the element and the mouse button is pressed and released. Any element HTML can receive this event.

Source: https://api.jquery.com/click/

$("#executar").click(function() {
  var campo = $("#busca").val();
  $("#result").html(campo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="busca" type="text" />
<button id="executar" type="button" class="btn btn-warning">Buscar</button>
<div id="result"></div>

  • 1

    It worked here man, thank you very much!!!! 2min to accept...

  • @Antônioleite I thank you in being able to help-Ló. Att.

-1

You can try something like this: $("#idBotao"). onclick(rest of function), I believe only this change will suffice.

  • 1

    I tested it just now, and it doesn’t work

  • $('selector'). on('click', Function(){}); $('selector'). click(Function(){}); ?

Browser other questions tagged

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