繁体   English   中英

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

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

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

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

我已经创建了一个数据库表,其中包含“已发货”状态的状态,因此,每当我单击“标记为已发货”按钮时,单词“已发货”都将进入带有订单ID的数据库表中,然后我要这个词运回了那个按钮,并无限期地停留在那里。 直到我更改了Ajax脚本的操作,PHP查询的效果都很好。

这是我的桌子。

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>

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

<?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}),
        });
    }   

然后,在按钮中,我将在onclick中调用该函数

<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的基本代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM