Validate Form without page change

0

I have a certain input of type submit that when clicking acts on a pagina.php . I wanted to do this, but when I clicked it it would not change pages, but it would act on that 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')");
    }
?>
    
asked by anonymous 06.03.2016 / 02:24

1 answer

1

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 this we have to add the script to download the jQuery library on your site.

Add the following tag in your header

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

Now you will have to make 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.
});
    
06.03.2016 / 03:20