Validate Form without changing page

Asked

Viewed 2,390 times

0

I have a certain input of type submit that when clicking acts on a pagina.php. I wanted you to do this, but when you clicked it didn’t change the page, but act on this one pagina.php.

HTML:

<html>
    <form method="post" action="inserir.php">
        <input type="submit" value="Enviar!">
    </form>
</html>

PHP:

<?php
    $link = mysqli_connect("localhost", "root", "vertrigo", "csgodouble");

    $contador = "0";
    while($contador < 10000){
        $contador++;
        $numero = rand(0, 14);
        $sql = mysqli_query($link, "INSERT INTO apostas (numero_sorteado, hash, data_f, status) VALUES ('$numero', '0', '0', '0')");
    }
?>
  • Already tried using Ajax?

  • I have no knowledge of ajax.

  • To be able to make a request to the server and act on the existing screen without updating the page it is necessary to use ajax. If you could put a piece of form code you are sending and how your php is getting it would be easier to help solve your problem.

  • I edited the question Vinicius.

  • You use jQuery or pure javascript?

  • How to give it more power Vinicius, for me it is indifferent.

Show 1 more comment

1 answer

3

First your form should have an id so we can identify it with javascript

<html>
<form id="myform" method="post" action="inserir.php">
  <input type="submit" value="Enviar!">
  </form>
  </html>

After that we have to add the script to download the jQuery library on your site.

Add the following tag to your header

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

Now you will have to do a javascript to send the request to your server using Ajax when you click the Submit button.

$("#myform").submit(function(e) {
    var url = "inserir.php"; 
    $.ajax({
           type: "POST",
           url: url,
           data: $("#myform").serialize(),
           success: function(data)
           {
               alert(data);
               //utilizar o dado retornado para alterar algum dado da tela.
           }
         });

    e.preventDefault();// esse comando serve para previnir que o form realmente realize o submit e atualize a tela.
});

Browser other questions tagged

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