-1

I have this code to create the forms:

<select id="mudar_produto"> 
    <option value="#produto_1">Novo Produto Higiene</option> 
    <option value="#produto_2">Entrada de Produtos Higiene</option>  
</select> 
<section class="hide-section" id="produto_1"> 
<form name="primeiro" id="primeiro" method="POST" action="./inserir">
    <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 type="submit" name="submit" class="botao submit">Registo</button>
</form>

</section> 



<section class="hide-section" id="produto_2"> 
    <form name="segundo" id="segundo" method="POST" action="./inserir"> 
         <fieldset> 
            <h1>
                <legend>
                    <center>
                        <strong>Entrada de Produtos de Higiene</strong>
            </center>
        </h1><br>       
        <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> 
        </div>
    <div class="campo"> 
        <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">
        </div>
    <div class="campo"> 
        <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 type="submit" name="submit1" class="botao submit">Registo</button>
    </form>
</section>

Then I have this script, where the first is to change form and the second not to refresh the page and keep the form open, but it is not working:

<script type="text/javascript"> 
$(document).ready(function(){ 
    $(".hide-section:not(:first)").hide();
    $('#mudar_produto').change(function(){
        $('.hide-section').hide();
        $($(this).val()).show();
    });
    $('#first_dd').change(function(){ 
        var id = $('#first_dd option:selected').val(); 
        $.each($('#second_dd option'),function(){ 
            if($(this).attr('data-id')==id){ 
                $(this).attr('selected',true); 
            }
        }); 
    });
    //Adicona o ouvinte de evento
document.getElementById('primeiro').addEventListener('submit', async function(e) {
    //Cria uma variável response com a resposta do fetch
    //this.action pega o action do form e seta como url de envio
    res = await fetch(this.action, {
        //this.method pega o atributo method do form e seta no method da requisição
        method: this.method,
        //O body contém os dados que devem ser enviados, o FormData(this) passa os dados com o nome e valor de cada entrada do form 
        body: new FormData(this)
    })
    //Retorna os dados para a variável res
    .then(data => data)
    //Se ocorrer algum erro mostra no console
    .catch(error => console.log(error));

    //Impede que o form seja submetido e mude de página
    e.preventDefault();
});
});
</script>

In the page teste2 I make the insertion of the data in the table of the database:

<?php

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

  $name = $_POST['DescricaoProd'];
  $unid = $_POST['DescricaoUnid'];    

$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";

if ($conn->query($sql) === TRUE);

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

if ($conn->query($sql1) === TRUE);

    //Count total number of rows
    $rowCount = $query->num_rows;

$conn->close();
return "completed";
}
?>

<?php
if(isset($_POST['submit1'])){

  $data = $_POST['DataEntrada'];
  $produto = $_POST['Produto'];  
  $unidade = $_POST['Unid'];   
  $quantidade = $_POST['Quantidade'];
  $preco = $_POST['Preco']; 


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

if ($conn->query($sql) === TRUE);

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

 if ($conn->query($sql1) === TRUE);

    //Count total number of rows
    $rowCount = $query->num_rows;

$conn->close(); 
return "completed";
}
?>

The script is not keeping the form open when I click the registration button, but it inserts into the database table

Bruno
  • 801
  • 5
  • 11
  • Are you looking for something like [this](https://stackoverflow.com/a/25983643/5957296)? AJAX is probably your best bet for moving data to and fro without affecting the page. – Guest May 23 '18 at 09:08
  • @Guest, Can you put an example to see how it works? – Bruno May 23 '18 at 09:10
  • Well since you're using jQuery, the link basically tells you exactly how to do it: write a function that, when called, takes your form and submits an AJAX request to your PHP file; then, when you press the "submit" button, have it call said function. The answer is pretty well written. – Guest May 23 '18 at 09:17
  • @Guest, I'm sorry, I did not notice that your comment had a link – Bruno May 23 '18 at 09:20
  • @Guest, I could not apply the example that put the link, is it because I use wordpress? – Bruno May 23 '18 at 14:41
  • What did you try and what happened when you did? – Guest May 24 '18 at 08:42

1 Answers1

0

After the line with

e.preventDefault();

Put in

return false;

e.preventDefault(); prevent any other element getting the event. Return false prevents on submit from completing.

Or try:

<button type="submit" name="submit" class="botao submit" onclick="return false;">Registo</button>

Or try:

<input type="button" class="botao submit">Registo</input>
John
  • 3,716
  • 2
  • 19
  • 21