我正在尝试使用ajax php和mysql,pdo在我的产品数据库中插入新产品。表单位于另一个html文件中,并在按下添加产品按钮后立即以引导程序模式加载。

下面是表格

<div class="container">
     <form class="form" id="insert-product" method="POST">
              <div class="form-group">
                  <label class="form-label" for="name">Product Title</label>
                  <input type="text" class="form-control" id="title" name="ptitle"  tabindex="1" required>
              </div>
               <div class="form-group">
                  <label class="form-label" for="message">Product Description</label>
                  <input type="text" class="form-control" id="desc" name="description" tabindex="2" required>
              </div>
              <div class="form-group">
                  <label class="form-label" for="email"> Price</label>
                  <input type="text" class="form-control" id="price" name="price" tabindex="2" required>
              </div>
              <div class="form-group">
                  <label class="form-label" for="subject">Picture of Product</label>
                  <input type="text" class="form-control" id="subject" name="picture"  tabindex="3">
              </div>

              <div class="text-center">
                  <button type="submit" name="submit" class="btn btn-start-order">SAVE</button>
              </div>
          </form>
      </div>
  </div>


这是使用ajax与php文件联系的脚本。 readProducts()是一个简单的函数,可从数据库中获取数据。

   $('#insert-product').on('submit', function(event) {
           event.preventDefault();
           $.ajax({
                    url: 'insertPro.php',
                    type: 'POST',
                    data: $('#insert-product').serialize(),
                    success: function(data) {

                        readProducts();
                    }

                 });
       })


这是将数据插入数据库的php文件。 connect.php经过测试,可以正常工作。

<?php
require_once('connect.php');

if (!empty($_POST)) {
    $response = array();

    $query = "insert into products(id,name,description,img_file,price) values(:title, :description, :picture, :price)";
    $stmt = $DBcon->prepare( $query );

    $stmt->bindParam(':title', $title);
    $stmt->bindParam(':description', $description);
    $stmt->bindParam(':picture', $picture);
    $stmt->bindParam(':price', $price);

    $title = $_POST["ptitle"];
    $description = $_POST["description"];
    $price = $_POST["price"];
    $picture = $_POST["picture"];

    $stmt->execute();

    if ($stmt) {
        $response['status']  = 'success';
        $response['message'] = 'Product Deleted Successfully ...';
    } else {
        $response['status']  = 'error';
        $response['message'] = 'Unable to delete product ...';
    }
}


这是我的连接文件。

<?php

    $DBhost = "localhost";
    $DBuser = "root";
    $DBpass = "";
    $DBname = "test";

    try{

        $DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
        $DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }catch(PDOException $ex){

        die($ex->getMessage());
    }

?>


当我按下按钮提交数据时,ajax会按应有的方式刷新,但记录未添加到数据库表中。

最佳答案

我假设id表的products列是一个自动增量列。

在这种情况下,您可以将其保留在列列表中,或者将其设置为NULL

所以要么

$query = "insert into products(name,description,img_file,price)
                        values(:title, :description, :picture, :price)";


要么

$query = "insert into products(id,name,description,img_file,price)
                        values(NULL, :title, :description, :picture, :price)";


同样在此脚本的结尾,您构建了一个响应,但实际上从未将其发送回AJAX调用。

$stmt->execute();

if ($stmt) {
    $response['status']  = 'success';
    $response['message'] = 'Product Deleted Successfully ...';
} else {
    $response['status']  = 'error';
    $response['message'] = 'Unable to delete product ...';
}
// add this line
echo $json_encode($response);


然后将dataType: 'JSON',添加到AJAX参数中,就可以将data中的结果作为javascritp对象进行处理

    $.ajax({
        url: 'insertPro.php',
        type: 'POST',
        data: $('#insert-product').serialize(),
        dataType: 'JSON',

10-06 16:00
查看更多