Send data without PHP refresh

Asked

Viewed 1,200 times

0

I have a form with n tables involved and needed to leave all the Insert in one file only, well this I already have. But I need it sent without refresh and for that I am using ajax. Here is the question how to do this in ajax, in a way that only data is sent that received click the button with the same name in the form ? Here’s a simple example I’ve 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>

parses.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;
}
  • starts the error that the two Forms have the same id. ID is something unique and cannot be repeated on the same page.

  • then but even without the second form having the id identico, the process goes through all the file instead of going through only user and password, it would have to have some stop point for it just read the user block and password and the second only read the block street and in a

1 answer

1


As has been said in other posts and for those who are starting with HTML, within a specific HTML page can never repeat Ids, the meaning of ID is probably:

IDentity Document (translated identity document)

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

  • document.getElementById
  • $(selector)

They will only consider one of the elements, the other is always ignored

To facilitate just exchange for another attribute, as class or data- (Html5).

Another problem is with the function jQuery.serialize jQuery, he ignores the type=submit, then 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

So 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 is 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>

Browser other questions tagged

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