简体   繁体   中英

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". 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. I've never used Ajax before or too much JS, so I'm not too sure on how to use the two simultaneously.

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. The php query was working great until I changed the action of the Ajax script.

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

    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

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

I would go with using something like this

JSON Object by Ajax:

$( "#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:

    $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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