使用 Ajax 和 PHP 在我的数据库中插入结果,然后显示它


Using Ajax and PHP to insert a result in my db and then display it

我正在尝试创建一个运输状态页面,我希望一个非常基本的功能能够正常工作。我希望能够按下此页面上显示"标记已发货"的按钮。然后我希望按钮的文本更改为"已发货"。然后,我希望该选项将其状态更改回"标记已发货",但有一个警报阻止它执行此操作,直到您单击"继续"或类似内容。

我正在尝试用php和ajax来做到这一点。我以前从未使用过Ajax或太多的JS,所以我不太确定如何同时使用两者。

我创建了一个数据库表,该表将容纳"已发货"状态的状态,因此每当我单击"标记为已发货"按钮时,"已发货"一词将带有订单 id 进入我的数据库表,然后我希望单词已发货回显到该按钮并无限期地保留在那里。php 查询运行良好,直到我更改了 Ajax 脚本的操作。

所以这是我的桌子..

if( $result ){  
while($row = mysqli_fetch_assoc($result)) :
?>
                 <form method="POST" action="shippingStatus.php">
                    <tr>
                        <td class="tdproduct"><?php echo $row['order_id']; ?> </td>
                        <td class="tdproduct"><?php echo $row['date_ordered']; ?> </td> 
                        <td class="tdproduct"><?php echo $row['customer_name']; ?> </td>
                        <td class="tdproduct"><?php echo $row['streetline1'] . "<br />" . $row['streetline2'] . "<br />" . $row['city'] . ", " . $row['state'] . " " . $row['zipcode']; ?> </td>
                        <td class="tdproduct"><?php echo $row['product_name']; ?> </td>
                        <td class="tdproduct"><button data-text-swap="Shipped">Mark Shipped</button></td>
                        <input type="hidden" name="product_id" value="<? echo $row['id']; ?>"/>
                        <td class="tdproduct"><input name="delete" type="submit" value="DELETE "/></td>
                    </tr>
                </form>
<?php   
  endwhile; 
  }
?>
                </table>

这是我的 Ajax 脚本。起初我以"发货"作为操作,但它没有保存状态。当我重新加载页面时,它会回到"标记已发货"。

<script>
$("button").on("click", function(e) {
    e.preventDefault()
    var el = $(this);
    $.ajax({
        url: "shippingStatusSend.php",
        data: {action: "<?php echo $shipped; ?>", order: order_id},
        type: "POST",
        dataType: "text"
        }).fail(function(e,t,m){
        console.log(e,t,m); 
    }).done(function(r){
        //Do your code for changing the button here.
        //Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
        el.text() == el.data("text-swap") 
        ? el.text(el.data("text-original")) 
        : el.text(el.data("text-swap"));
    });
});
</script>

我在一个名为shippingStatusSend的页面中的php:

<?php
//connection to db
$con = mysqli_connect("localhost", "root", "", "bfb"); 
//Check for errors  
if (mysqli_connect_errno()) {
    printf ("Connect failed: %s'n", mysqli_connect_error());
    exit();
}
    $order_id = trim($_POST['order_id'] );
    $status = trim($_POST['action'] );
    $shipped = "Shipped";
    $markshipped = "Mark Shipped";
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "INSERT INTO shippingStatus (order_id, status, date_Shipped) VALUES (?, ?, NOW())")) {
/* bind parameters for markers */
            $stmt->bind_param('is', $order_id, $status);
        /* execute query */
        $stmt->execute();
        echo $shipped;
    /* close statement */
    mysqli_stmt_close($stmt);
        }
        while($row = mysqli_fetch_assoc($stmt)){
        $shipped = $row['status'];
        $markshipped = "Mark Shipped";
        }
        else 
        echo $markshipped;
?>

不确定我做错了什么,谁能指出我错在哪里的方向?是我的php代码还是我尝试使用Ajax执行此操作的方式,或者两者兼而有之。我的代码的哪个区域是错误的?

似乎不对。

 data: {action: "<?php echo $shipped; ?>", order: order_id},

我会尝试将参数添加到 ajax 脚本中并将它们用于 POST,而不是尝试内联访问 php 变量。

    function insert(anAction, anOrder){
        $.ajax({
           url: 'shippingStatusSend.php',
           dataType: 'json',
           type: "POST",
           data: ({action: anAction, order: anOrder}),
        });
    }   
然后,在

按钮中,我只需在单击中调用该函数

<button id="some_button" onclick="insert(<?php echo $row['action'] . ',' . $row['order_id']; ?>)"
如果你

打算使用JQuery/Ajax,我会尽量不使用内联JavaScript,如onclick="

我会使用这样的东西

Ajax 的 JSON 对象:

$( "#buttonID" ).on( "click", function() {
     var newObject = {};
     newObject.order_id = "newOrderID";
     $.post("phpFile", 
     {
         action: "newAction",
         sendObject: JSON.stringify(newObject)
     })
     .success(function(data) 
     {
        // Returned data, you can use this to display whatever you need
        // on the page
        console.log(data);
     });
});

PHP代码:

    $action = $_POST['action'];
    if ($action == 'newAction') 
    {
        $receivedObject = json_decode($_POST['sendObject'], true);
        $orderID = $receivedObject['order_id'];
        echo $orderID;
    }

现在你只需要拿这个代码,用它来更新或插入数据到数据库中,这是使用Ajax将其发送到php的基本代码