Send data without refresh PHP [closed]

0

I have a form with n tables involved and needed to leave all the insert in a single file, well this I already have. But I need it to be sent without refresh and for this I am using ajax. Here's the question how to do this in ajax, in a way that only the data that gets clicked from the button with the same name in form is sent? Here is a simple example I created now to demonstrate my idea.

index.php

<script type="text/javascript">
$(document).ready(function(){
        $('#ajax_form').submit(function(){
                var dados = jQuery( this ).serialize();

                $.ajax({
                        type: "POST",
                        url: "processa.php",
                        data: dados,
                        success: function( data )
                        {
                                alert( data );
                        }
                });

                return false;
        });
});
</script>
</head>
<body>
<form method="post" action="" id="ajax_form">
        <label>Usuário: <input type="text" name="usuario" value="" /></label>
        <label>Senha: <input type="text" name="senha" value="" /></label>       
        <label><input type="submit" name="enviar" value="Enviar" /></label>
</form>
<form method="post" action="" id="ajax_form">
        <label>Rua: <input type="text" name="rua" value="" /></label>
        <label>Número: <input type="text" name="numero" value="" /></label>     
        <label><input type="submit" name="enviar2" value="Enviar" /></label>
</form>

processa.php

if(isset($_POST['enviar'])){

    $usuario = $_POST['usuario'];
    $senha = $_POST['senha'];

    $sql = "SELECT * FROM usuar";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();

    $resultx= "INSERT INTO usuar (usuario, senha) VALUES ('$usuario', '$senha')";
    $resultado = mysqli_query($conn, $resultx);
    echo $resultx;
}


if(isset($_POST['enviar2'])){

    $rua = $_POST['rua'];
    $num = $_POST['num'];

    $sql2 = "SELECT * FROM userend";
    $result = $conn->query($sql2);
    $row = $result->fetch_assoc();

    $resulty = "INSERT INTO userend (rua, numero) VALUES ('$rua', '$num')";
    $resultado = mysqli_query($conn, $resulty);
    echo $resulty;
}
    
asked by anonymous 27.09.2017 / 19:14

1 answer

1

As already stated in other posts and for those who are starting with HTML, within a specified HTML page can never be repeated IDs, the meaning of ID is probably:

  

I dentity D ocument (translated identity document)

That is, if two objects have the same ID already causes confusion, and functions like:

  • document.getElementById
  • $(selector)

They will only consider one element, the other is always ignored

To facilitate, simply change to another attribute, such as class or data- (html5).

Another problem is with the function jQuery.serialize of jQuery, it ignores type=submit , so you have to manually add an example:

var dados = jQuery(this).serialize();

$("[type=submit]", this).each(function () {
     dados += "&" + escape($(this).attr("name")) + "=" + escape($(this).val());
});

I also recommend using Event.preventDefault

Then the code should look like this:

<script type="text/javascript">
$(document).ready(function(){
        $('.ajax_form').submit(function(e){
                e.preventDefault();

                var dados = jQuery(this).serialize();

                $("[type=submit]", this).each(function () {
                     dados += "&" + escape($(this).attr("name")) + "=" + escape($(this).val());
                });

                $.ajax({
                        type: "POST",
                        url: "processa.php",
                        data: dados,
                        success: function( data )
                        {
                                alert( data );
                        }
                });

                return false;
        });
});
</script>
</head>
<body>
<form method="post" action="" class="ajax_form">
        <label>Usuário: <input type="text" name="usuario" value="" /></label>
        <label>Senha: <input type="text" name="senha" value="" /></label>       
        <label><input type="submit" name="enviar" value="Enviar" /></label>
</form>
<form method="post" action="" class="ajax_form">
        <label>Rua: <input type="text" name="rua" value="" /></label>
        <label>Número: <input type="text" name="numero" value="" /></label>     
        <label><input type="submit" name="enviar2" value="Enviar" /></label>
</form>

Test without Ajax

Test to see what's sent:

$(document).ready(function(){
    $('.ajax_form').submit(function(e) {
        e.preventDefault();

        var dados = jQuery(this).serialize();

        $("[type=submit]", this).each(function () {
             dados += "&" + escape($(this).attr("name")) + "=" + escape($(this).val());
        });

        console.log(dados);

        return false;
    });
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form method="post" action="" class="ajax_form">
    <label>Usuário: <input type="text" name="usuario" value="" /></label>
    <label>Senha: <input type="text" name="senha" value="" /></label>       
    <label><input type="submit" name="enviar" value="Enviar" /></label>
</form>

<form method="post" action="" class="ajax_form">
    <label>Rua: <input type="text" name="rua" value="" /></label>
    <label>Número: <input type="text" name="numero" value="" /></label>     
    <label><input type="submit" name="enviar2" value="Enviar" /></label>
</form>
    
27.09.2017 / 19:47