Insert into database table with second form

Asked

Viewed 67 times

3

I have this menu:

<nav class="menu">
  <ul class="menu-list">
        <li><a href="#">Produtos de Higiene</a>
                <ul class="sub-menu">
                    <li><a href="#produto_1">Novo</a></li>
                    <li><a href="#produto_2">Entrada</a></li>
                </ul>
        </li>
  </ul>
</nav>

Then I have these two forms:

<section class="hide-section" id="produto_1"> 
<form class="form-validate" id="feedback_form">
    <div class="campo">
        <fieldset> 
            <h1>
                <legend>
                    <center>
                        <strong>Produtos de Higiene</strong>
            </center>
        </h1><br> 
        </div>
        <fieldset class="grupo">
    <div class="campo">
            <strong><label for="Nome do Produto">Nome do Produto</label></strong> 
            <input type="text" id="DescricaoProd" name="DescricaoProd" required="" style="width:350px">
        </div>
    <div class="campo"> 
        <strong><label for="Unidade">Unidade</label></strong> 
            <input type="text" id="DescricaoUnid" name="DescricaoUnid" style="width:160px" required="" size="120">
        </div>
        </fieldset>
        <button class="btn btn-success btn_contact" type="button">Registo</button>
        <div id="success_messages" class="hide">sucessso</div>
        <div id="error_message" class="hide">erro</div>
</form>
</section> 


<section class="hide-section" id="produto_2"> 
<form name="form1" id="form1" class="form-validate" id="feedback_form"> 
    <div class="campo">
         <fieldset> 
            <h1>
                <legend>
                    <center>
                        <strong>Entrada de Produtos de Higiene</strong>
            </center>
        </h1><br> 
    </div>      
        <fieldset class="grupo">
    <div class="campo">
            <strong><label for="Data Entrada">Data Entrada</label></strong>
            <input id="DataEntrada" type="date" name="DataEntrada" required="" style="width:180px" value="<?php echo date("Y-m-d");?>">
        </div>
        </fieldset>
        <fieldset class="grupo">
    <div class="campo"> 
        <strong><label for="Produto">Produto</label></strong>
        <select id="first_dd" name="Produto" style="width:250px" required> 
            <option></option> 
            <?php 
                $sql = "SELECT * FROM centrodb.ProdHigieneteste WHERE Ativo = 1 ORDER BY DescricaoProd ASC"; 
                $qr = mysqli_query($conn, $sql); 
                while($ln = mysqli_fetch_assoc($qr)){ 
                    echo '<option value="'.$ln['IDProd'].'"> '.$ln['DescricaoProd'].'</option>'; 
                    $valencia[$ln['IDProd']]=array('DescricaoUnid'=>$ln['DescricaoUnid'],'DescricaoUnid'=>$ln['DescricaoUnid']); 
                } 
            ?> 
        </select>
        <strong><label for="Unidade">Unidade</label></strong>
        <select id="second_dd" name="Unid" style="width:150px" required> 
            <option></option> 
            <?php
                foreach ($valencia as $key => $value) { 
                    echo '<option data-id="'.$key.'" value="'.$value['DescricaoUnid'].'">'.$value['DescricaoUnid'].'</option>'; 
                }
            ?> 
        </select><br> 
        </div>
        </fieldset>
        <fieldset class="grupo">
    <div class="campo"> 
        <strong><label for="Quantidade">Quantidade</label></strong>
            <input type="text" id="Quantidade" name="Quantidade" style="width:80px" required="" size="40">
        <strong><label for="Preço">Preço</label></strong>
            <input type="text" id="Preco" name="Preco" style="width:100px" value="0.00">
        </div>
    </fieldset>
        <button class="btn btn-success btn_contact" type="button">Registo</button>
        <div id="success_messages" class="hide">sucessso</div>
        <div id="error_message" class="hide">erro</div>
    </form>
</section> 

I have this script to send the data to the page where you have the php code for insert into the table:

<script type="text/javascript"> 
$(document).ready(function(){ 
$(".btn_contact").click(function () {

                $.ajax({
                    type: "POST",
                    url: "./inserir",
                    data: $("#feedback_form").serialize(), // serializes the form's elements.
                    dataType: "json",
                    success: function (data)
                    {
                            $(".success_messages").removeClass('hide'); // success message
                        }, 
                    error: function(data){
                            $(".error_message").removeClass('hide'); // error message
                        },
                    complete: function()
                    { 
                         $("#feedback_form").find('input').val(''); //clear text
                    } 
                });

            });
 });
</script>

Then I have the page where I have the php code to insert: Code 1 form:

<?php

$name = isset($_POST["DescricaoProd"]) ? $_POST["DescricaoProd"] : '';
$unid = isset($_POST["DescricaoUnid"]) ? $_POST["DescricaoUnid"] : '';

if (!empty($name) && !empty($unid)) {  
   echo json_encode("true");
} else {
    echo json_encode("false");
}

$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";
if ($conn->query($sql)) { // check for === TRUE is not necessary
   // either put the second query in here, or just enjoy the success
} else {
   // get the error, throw a message...
}

$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";

$query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

if ($conn->query($sql1) === TRUE) {
    //Count total number of rows
    $rowCount = $query->num_rows;
} else {
    // get the error, throw a message...
}


$conn->close();
?>

Code 2 form:

<?php

$data = isset($_POST["DataEntrada"]) ? $_POST["DataEntrada"] : '';
$produto = isset($_POST["Produto"]) ? $_POST["Produto"] : '';  
$unidade = isset($_POST["Unid"]) ? $_POST["Unid"] : '';   
$quantidade = isset($_POST["Quantidade"]) ? $_POST["Quantidade"] : '';
$preco = isset($_POST["Preco"]) ? $_POST["Preco"] : ''; 

if (!empty($data) && !empty($produto) && !empty($unidade) && !empty($quantidade) && !empty($preco)) {  
   echo json_encode("true");
} else {
    echo json_encode("false");
}

$sql2 = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco) 
VALUES ('$data','$produto','$unidade','$quantidade','$preco')";

if ($conn->query($sql2)) { // check for === TRUE is not necessary
   // either put the second query in here, or just enjoy the success
} else {
   // get the error, throw a message...
}

$sql3 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;

 $query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

if ($conn->query($sql3) === TRUE) {
    //Count total number of rows
    $rowCount = $query->num_rows;
} else {
    // get the error, throw a message...
}

$conn->close();
?>

The problem I have, is that when I register in the first form works well, inserts in the table and clears the form, but when I try to register in the second form does not insert in the table nor clears the form, and enter the tables in the first form and blank.

  • your Forms have no action?

  • @Matheusreis doesn’t need it, because he has the ajax to send the data to the page where php is, have in question that part of the code

3 answers

4


Ajax()

First the ajax() need to send information to distinguish in PHP what action you want to take:

$(document).ready(function(){ 
    $(".btn_contact").click(function () {
        var id = $(this).closest("section").attr("id");
        var serialize = $("#"+id+" form").serialize();
        serialize += "&type="+id;
        $.ajax({
            type: "POST",
            url: "./inserir",
            data: serialize,
            dataType: "json",
            success: function (data)
            {
                $(".success_messages").removeClass('hide'); // success message
            }, 
            error: function(data)
                {
                    $(".error_message").removeClass('hide'); // error message
                },
            complete: function()
                { 
                    $("#feedback_form").find('input').val(''); //clear text
                } 
        });
    });
});
  • var id = $(this).closest("section").attr("id"); picks up the id of section of the form that will be sent

  • var serialize = $("#"+id+" form").serialize(); serialize the form

  • serialize += "&type="+id; here it adds a new field to the var serialize which is the same id of section, he who will help you separate the shares in the PHP

PHP

Now the PHP has a unique identifier for you to be able to separate the actions, which is the $_POST['type']:

$_POST['type']='producto_1':

if($_POST['type']=='produto_1'):
    $name = isset($_POST["DescricaoProd"]) ? $_POST["DescricaoProd"] : '';
    $unid = isset($_POST["DescricaoUnid"]) ? $_POST["DescricaoUnid"] : '';

    if (!empty($name) && !empty($unid)) {  
       echo json_encode("true");
    } else {
        echo json_encode("false");
    }

    $sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) 
    VALUES ('$name','$unid')";
    if ($conn->query($sql)) { // check for === TRUE is not necessary
       // either put the second query in here, or just enjoy the success
    } else {
       // get the error, throw a message...
    }

    $sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) 
    VALUES ('$name','$unid')";

    $query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

    if ($conn->query($sql1) === TRUE) {
        //Count total number of rows
        $rowCount = $query->num_rows;
    } else {
        // get the error, throw a message...
    }
    $conn->close();
endif;

$_POST['type']='producto_2':

if($_POST['type']=='produto_2'):
    $data = isset($_POST["DataEntrada"]) ? $_POST["DataEntrada"] : '';
    $produto = isset($_POST["Produto"]) ? $_POST["Produto"] : '';  
    $unidade = isset($_POST["Unid"]) ? $_POST["Unid"] : '';   
    $quantidade = isset($_POST["Quantidade"]) ? $_POST["Quantidade"] : '';
    $preco = isset($_POST["Preco"]) ? $_POST["Preco"] : ''; 

    if (!empty($data) && !empty($produto) && !empty($unidade) && !empty($quantidade) && !empty($preco)) {  
       echo json_encode("true");
    } else {
        echo json_encode("false");
    }

    $sql2 = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco) 
    VALUES ('$data','$produto','$unidade','$quantidade','$preco')";

    if ($conn->query($sql2)) { // check for === TRUE is not necessary
       // either put the second query in here, or just enjoy the success
    } else {
       // get the error, throw a message...
    }

    $sql3 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;

     $query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

    if ($conn->query($sql3) === TRUE) {
        //Count total number of rows
        $rowCount = $query->num_rows;
    } else {
        // get the error, throw a message...
    }       
    $conn->close();
endif;

It is not the most appropriate practice, because I believe that it can be done in a way with less face of gambiarra, but as your system already works, and you want to solve the problem, it solves.

3

Both your Forms have the same id, And that’s bad practice. Your form is entering empty data because, when you give a Ubmit, it takes the data from the first form, which is empty, and inserts it into the database.

Try filling the two Forms, and see which data will be entered in the table. Surely it will be the first form, which has the first id feedback_form. Change the id's, so that they are different, and also change the logic, so that their Submit is "independent".

2

From what I’ve seen you detect the click on .btn_contact, a button that is in both forms, so far nothing wrong. But when it comes to pulling the data from the form you just pull an ID #feedback_form. So you’ll always pull the data from one form.

By changing your code a little I made the script search for the form on its own to always catch the one where the .btn_contact is inside:

<script type="text/javascript"> 
$(document).ready(function(){ 
    $(".btn_contact").click(function () {
            var myForm=$(this).closest("form");
            $.ajax({
                type: "POST",
                url: "./inserir",
                data: myForm.serialize(), // serializes the form's elements.
                dataType: "json",
                success: function (data)
                {
                        $(".success_messages").removeClass('hide'); // success message
                    }, 
                error: function(data){
                        $(".error_message").removeClass('hide'); // error message
                    },
                complete: function()
                { 
                     myForm.find('input').val(''); //clear text
                } 
            });

        });
});
</script>

I think that should do it, test it and tell me how it was!

  • A question @Beginner, the two forms should send to "./insert" even?

  • yes, that’s where I have the php code

  • I tested the code (apart from the PHP record part) and it is passing the data to AJAX so now it must be something in PHP itself, it comes to give some error when registering? Maybe some SQL error?

  • 5

    @Beginner Remember that the responsibility to make it work is yours, not who answers, so comments like "didn’t work" do not bring any benefit to the discussion or to the community. Instead of just copying/pasting the answer and executing, try to understand what was described in the answer, recognize what your error was and try to fix it with the tips given.

  • @Henrique Pauli, in php I get no error, the problem is that when entering with the second form he always uses the input code of the first form. When registering with the second form, I should ignore the first input code and insert with the second one...I think the problem is on the php side, because it sends the data, but I don’t know how to solve it

  • @Beginner, try creating a Hidden input with the name "action" (for example) in the two forms, in the first you define the value of "action" as "insert" and the other as "input". In your PHP code you check, if $_POST['acao']=="insert" then use the insert code, otherwise use the other PHP code.

Show 1 more comment

Browser other questions tagged

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