php - 向表发送数据时保持表单打开

标签 php html mysql ajax wordpress

我在同一页面中有多个表单的代码:

  • 测试 1 页面:

<select id="mudar_produto"> 
    <option value="#produto_1">Novo Produto Higiene</option> 
    <option value="#produto_2">Entrada de Produtos Higiene</option> 
    <option value="#produto_3">Novo Produto Nutricia</option> 
</select>

<section class="hide-section" id="produto_1">
    <form id="form3" action="./teste2" method="POST" onsubmit="return form_validation()"> 
        <fieldset> 
            <h1>
                <legend>
                    <center>
                        <strong>Produtos de Higiene</strong>
            </center>
        </h1><br> 
        <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="form4" action="./teste2" method="POST" onsubmit="return form_validation()"> 
         <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>   

<section class="hide-section" id="produto_3"> 
    <form id="form3" name="form3" action="./teste2" method="POST" onsubmit="return form_validation()" > 
        <fieldset> 
            <h1>
                <legend>
                    <center>
                        <strong>Produtos de Nutricia</strong>
            </center>
        </h1><br> 
        <fieldset class="grupo">
    <div class="campo">
            <strong><label for="Nome do Produto">Nome do Produto</label></strong>
                <input type="text" id="ProdNutricia" name="ProdNutricia" style="width:350px" required="" size="120" />
            </div> 
    </fieldset>
        <button type="submit" name="submit2" class="botao submit">Registo</button>
    </form> 
</section> 

在页面teste2中,我将数据插入数据库的表中:

<script language="javascript" type="text/javascript">
document.location = "teste1";
</script>

<?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;

header("Location: teste1");

$conn->close();
}
?>

<?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;

header("Location: teste1");

$conn->close(); 
}
?>

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

    $name = $_POST['ProdNutricia'];  

$sql = "INSERT INTO ProdNutriciateste (ProdNutricia) 
VALUES ('$name')";

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

$sql1 = "INSERT INTO StockNutriciateste (ProdNutricia) 
VALUES ('$name')";

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

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

header("Location: teste1");

$conn->close();
}
?>

在表中插入数据时一切正常,但是当我执行插入并执行标题时(“位置:teste1”);关闭我正在填写的表单,但我想将其保持打开状态,因为我可能需要在同一个表单上插入多种类型的产品。

最佳答案

一些开始的解释:

  1. 我已经清理了您的 HTML 标记。您可能已经获得了所需的外观,但标记已严重损坏。一个好的编辑器会帮助你制作一个well-formed文件 validates .
  2. 我用过Bootstrap用于造型。 Foundation是另一个不错的选择。
  3. JQuery用作Javascript事件监控和AJAX的基础
  4. 这不是复制和粘贴代码。未经测试;它的目的是为您指明正确的方向。
  5. 对代码进行了注释,以帮助您了解其用途。

由于这就是 SO 显示代码的方式,因此我们从 javascript 和 HTML 开始:

// this delays execution until after the page has loaded
$( document ).ready(function() {
  
  // this monitors the button, id=submit-form-1, for a click event
  // and then runs the function, submitForm1()
  $('#submit-form-1').on('click', function() {
    submitForm('#form1');
  });
  
  // could be repeated for another form...
  $('#submit-form-2').on('click', function() {
    submitForm('#form2');
  });
  
  
});

// this function does an AJAX call to "insert.php".
// it expects a reply in JSON.
function submitForm(whichForm) {
  var datastring = $(whichForm).serialize();

  // see what you're sending:
  alert('You would be sending: ' + datastring);

  $.ajax({
    type: "POST",
    url: "insert.php",
    data: datastring,
    dataType: "json",
    success: function(data) {
        if(data.status=='success') {
          alert('successfully uploaded');
        } else {
          alert('failed to insert');
        }
    },
    error: function() {
        alert("This example can't actually connect to the PHP script, so this error appears.");
    }
});
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section id="produto_1">
  <!-- 
    note that the form is identified with id="form1".  
    "id" has to be unique. Nothing else can have id="form1".
    There are no action nor method attributes, 
    since AJAX is submitting the form contents.
  -->
  <form class="form-horizontal" id="form1">
    <!-- 
      field named "action" will be used in PHP script 
    -->
    <input type="hidden" name="action" value="insert_form_1" />
    <!-- use CSS for styling, not <center>, <strong>, etc. -->
    <h1 class="text-center">Produtos de Higiene</h1>
    <div class="form-group">
      <label for="DescricaoProd" class="col-sm-2 control-label">Nome do Produto</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="DescricaoProd" name="DescricaoProd" required />
      </div>
    </div>
    <div class="form-group">
      <label for="DescricaoUnid" class="col-sm-2 control-label">Unidade</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="DescricaoUnid" name="DescricaoUnid" required />
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-2">
        <!-- 
          button type is button, not submit.
          Otherwise the form will try to submit.
          We want the javascript to submit, not the form.
        -->
        <button type="button" id="submit-form-1" class="btn btn-success">Registo</button>
      </div>
    </div>
  </form> 
</section>

<!-- set up another form in the same way... -->
<form id="form2">
<input type="hidden" name="action" value="insert_form_2" />
...
<button type="button" id="submit-form-2">submit form 2</button>
</form>

上述标记和 javascript 应向 insert.php 发出 AJAX POST 请求,并监听回复。

插入.php

<?php

/**
  * note:  It is a good practice to NEVER have anything before the <?php tag.
  * 
  * Always try to separate logic from presentation.  This is why you should 
  * start with PHP on the top, and never do any output until you are done
  * with processing.  Better yet, have separate files for logic and presentation
  *
  */ 

// if $_POST doesn't have ['action'] key, stop the script. Every request will have
// an action.
if(!array_key_exists('action', $_POST)) {
  die("Sorry, I don't know what I'm supposed to do.");
}


// database initialization could (should) go on another page so it can be reused!
// set up PDO connection
// this section credit to https://phpdelusions.net/pdo
// use your credentials here...
$host = '127.0.0.1';
$db   = 'your_db_name';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";

// helpful initializations, such as default fetch is associative array
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

// instantiate database
$pdo = new PDO($dsn, $user, $pass, $opt);

// end database initialization


// whenever you have to do something over again, break it out into a function
// this function prevents warnings if the variable is not present in $_POST
function get_post($var_name) {
  $out = '';
  if(array_key_exists($var_name,$_POST)) {
    $out = $_POST[$var_name];
  }
  return $out;
}



// assign variables
$action = get_post('action');
$name = get_post('DescricaoProd');
$unid = get_post('DescricaoUnid');    


// All output of this script is JSON, so set the header to make it so.  
// There can be NO output before this!
// Not even a blank line before the <?php start tag.
header('Content-Type: application/json');


// take action based on value of "action".  

if($action=='insert_form_1') {

    $error = false;
    $output = array('message' => 'success');

    // Use placeholders, never (NEVER NEVER NEVER) php variables!
    $sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
    $pdo->prepare($query);
    $result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
    if(!$result) { $error = true; }

    $sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
    $pdo->prepare($query);
    $result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
    if(!$result) { $error = true; }

    // note, I just repeated myself, so this probably should be refactored...

    // send a message back to the calling AJAX:
    if($error) {
        $output = array('status' => 'failed');
    } else {
        $output = array('status' => 'success');
    }

    print json_encode($output);
    die; // nothing more to do

}

// you could have additional actions to perform in the same script.
// or, you could use different files...

if($action=='insert_form_2') {
    // do insert for form 2
}

// etc.

关于php - 向表发送数据时保持表单打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477579/

相关文章:

php - SQL INSERT INTO SELECT 并返回 SELECT 数据以创建行 View 计数

javascript - 如何让球左右移动?

html - HTML选择上的水平滚动?

php - 如何防止插入重复记录?

mysql - MySQL中两个日期列的算术计算

php - 使用 Yii 模型创建或更新多个 mysql 行

php - 在 wordpress 插件页面中添加可拖动部分

javascript - 将窗口调整大小事件分别附加到每个元素

jquery - 响应式折叠菜单不起作用

php - 在两个具有不相同表的mysql表中搜索(关键字搜索)