简体   繁体   English

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

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

I'm attempting to create a shipping status page and I want a really basic feature to work. 我正在尝试创建运输状态页面,并且我希望一个真正的基本功能能够正常工作。 I want to be able to press a button on this page that says "Mark Shipped". 我希望能够按此页面上显示“已发货标记”的按钮。 Then I want the button's text to change to "Shipped". 然后,我希望按钮的文本更改为“ Shipped”。 I then want the option to change the status of that back to "Mark Shipped', but have an alert prevent it from doing it until you click Proceed or something like that. 然后,我希望该选项将其状态更改回“标记为已发货”,但有一个警报阻止它执行此操作,直到您单击“继续”或类似的操作。

I am attempting to do this with php and ajax. 我试图用php和ajax做到这一点。 I've never used Ajax before or too much JS, so I'm not too sure on how to use the two simultaneously. 我以前从未使用过Ajax或使用过太多的JS,因此我不太确定如何同时使用两者。

I have created a database table that will house the status of the 'shipped' status, so whenever I click the 'mark as shipped' button the word 'shipped' will go into my db table with the id of the order and then I want the word shipped to echo back into that button and remain there indefinitely. 我已经创建了一个数据库表,其中包含“已发货”状态的状态,因此,每当我单击“标记为已发货”按钮时,单词“已发货”都将进入带有订单ID的数据库表中,然后我要这个词运回了那个按钮,并无限期地停留在那里。 The php query was working great until I changed the action of the Ajax script. 直到我更改了Ajax脚本的操作,PHP查询的效果都很好。

So this is my table.. 这是我的桌子。

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>

This is my Ajax script. 这是我的Ajax脚本。 At first I had 'shipped' as the action, but it wasn't saving the status. 起初,我以“装运”为行动,但并没有保存状态。 When I would reload the page it would go back to 'Mark Shipped'. 当我重新加载页面时,它将返回到“标记为已发货”。

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

My php in a page called shippingStatusSend: 我的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;
?>

I am not sure what I am doing wrong, could anyone point me in the direction of what is wrong? 我不确定自己在做什么错,有人能指出我错了吗? Is it my php code or the way I'm attempting to do this with Ajax or both. 是我的php代码还是我尝试使用Ajax或两者兼而有之的方式。 Which area of my code is wrong? 我的代码的哪个区域错误?

This doesn't seem right. 这似乎不正确。

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

I would try adding parameters to the ajax script and use those for the POST instead of trying to access the php variable in-line. 我会尝试将参数添加到ajax脚本中,并将其用于POST,而不是尝试直接访问php变量。

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

then, in the button I'd just call the function in an onclick 然后,在按钮中,我将在onclick中调用该函数

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

If you're going to be using JQuery/Ajax I would try and get away from using inline JavaScript such as onclick="" 如果您要使用JQuery / Ajax,我将尝试摆脱使用内嵌JavaScript(例如onclick =“”)的麻烦

I would go with using something like this 我会去使用这样的东西

JSON Object by Ajax: 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 Code: PHP代码:

    $action = $_POST['action'];

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

        echo $orderID;
    }

Now you just need to take this code and use it to update or insert the data into the database, this is the basic code using Ajax sending it to php 现在,您只需要使用此代码并将其用于更新数据或将数据插入数据库,这是使用Ajax将其发送到php的基本代码

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

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