Insert into the database table with the second form

4

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 it has the php code for insert in 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 1st 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 on the first form it works fine, inserts it in the table and clears the form, but when I try to register on the second form it does not insert into the table nor clean the form, and it registers in the tables of the first form and blank.

    
asked by anonymous 03.07.2018 / 13:09

3 answers

5

Ajax ()

First of all, ajax() needs to send information to distinguish in% with% of 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
                } 
        });
    });
});
  • PHP gets the id of the var id = $(this).closest("section").attr("id"); of the form that will be sent

  • section serializes the form

  • var serialize = $("#"+id+" form").serialize(); here it adds a new field to serialize += "&type="+id; which is the same var serialize of id , it will help you to separate actions in section

PHP

PHP now has a unique identifier for you to separate actions, which is PHP :

$ _ POST ['type'] == 'product_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'] == 'product_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 it can be done in a less expensive way, but as your system already works, and you want to solve the problem, that solves it.

    
03.07.2018 / 14:17
3

Both your forms have the same id , and this is a bad practice. Your form is inserting empty data because, when you give a submit, it takes the data from the first form, which is empty, and inserts it into the database.

Try to fill in both forms, and see what data will be inserted into the table. Of course, they will be those of 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 the submit of them is "independent".

    
03.07.2018 / 13:32
2

From what I saw you detect the click on .btn_contact , a button that is in both forms, so far nothing wrong. But at the time of pulling form data you just pull a #feedback_form ID. So it will always pull the data from a form only.

Changing your code a bit, I've made the script look for the form on its own to always get the one where .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 this should solve, test there and tell me how it was!

    
03.07.2018 / 13:36