将项目添加到我的购物车PHP时Ajax的问题

时间:2018-05-05 00:01:50

标签: javascript php jquery ajax

我刚刚开始学习如何编程,而且在向购物车添加商品时我遇到了ajax的问题​​。在添加项目时,一切都很好,它的ajax不起作用,我的页面不断保持清爽。对于代码,因为有很多代码,我会把我认为最重要的东西。

的index.php

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title></title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){


        $(document).on('click', '.add_to_cart', function(){
    var product_id = $(this).attr("id");
    var product_name = $('#name'+product_id+'').val();
    var product_price = $('#price'+product_id+'').val();
    var product_quantity = $('#quantity'+product_id).val();
    if(product_quantity > 0)
    {
        $.ajax({
            url:"index.php",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity},
            success:function(data)
            {
                alert("Item has been Added into Cart");
            }
        });
    }
    else
    {
        alert("lease Enter Number of Quantity");
    }
});

    });
</script>
</head>
<body>
<header>
<?php
include_once'widget/header.php';
    if (isset($_SESSION['u_id'])) {
    include_once"include/addcart.php";
    include_once "widget/shoppingcart.php";
}
?>
</header>
<main>
<div class="item-container">
    <?php
        $item = mysqli_query($db,"SELECT * FROM itemlist ORDER BY title");  
        include_once 'widget/container.php';
    ?>
</div>
</main>

Addcart.php

<?php

    $row_ids = array();
    //session_destroy();

    //check if Add to Cart button has been submitted
    if(filter_input(INPUT_POST, 'add_to_cart')){
        if(isset($_SESSION['shopping_cart'])){

            //keep track of how mnay products are in the shopping cart
            $count = count($_SESSION['shopping_cart']);

            //create sequantial array for matching array keys to products id's
            $row_ids = array_column($_SESSION['shopping_cart'], 'id');

            if (!in_array(filter_input(INPUT_POST, 'id'), $row_ids)){
            $_SESSION['shopping_cart'][$count] = array
                (
                    'id' => filter_input(INPUT_POST, 'id'),
                    'name' => filter_input(INPUT_POST, 'name'),
                    'price' => filter_input(INPUT_POST, 'price'),
                    'quantity' => filter_input(INPUT_POST, 'quantity')
                );
                // header("Location:index.php?addedtocart");
            }
            else { //product already exists, increase quantity
                //match array key to id of the product being added to the cart
                for ($i = 0; $i < count($row_ids); $i++){
                    if ($row_ids[$i] == filter_input(INPUT_POST, 'id')){
                        //add item quantity to the existing product in the array
                        $_SESSION['shopping_cart'][$i]['quantity'] += filter_input(INPUT_POST, 'quantity');
                        // header("Location:index.php?multtocart");
                    }
                }
            }

        }
        else { //if shopping cart doesn't exist, create first product with array key 0
            //create array using submitted form data, start from key 0 and fill it with values
            $_SESSION['shopping_cart'][0] = array
            (
                'id' => filter_input(INPUT_POST, 'id'),
                'name' => filter_input(INPUT_POST, 'name'),
                'price' => filter_input(INPUT_POST, 'price'),
                'quantity' => filter_input(INPUT_POST, 'quantity')
            );
        }
    }
    if (filter_input(INPUT_POST, 'delete')) {
        //loop thru intil products in shop cart == variable
        foreach ($_SESSION['shopping_cart'] as $key => $row) {
            if ($row['id'] == filter_input(INPUT_POST, 'id')) {
                unset($_SESSION['shopping_cart'][$key]);
            }
        }
        $_SESSION['shopping_cart'] =array_values($_SESSION['shopping_cart']);
    }

    ?>

Shoppingcart.php

<div class="cart-container" align="right">
            <div class="table-responsive">  
            <table class="table">  
            <table class="table">  
                <tr><th colspan="5"><h5>Order Details</h5></th></tr>   
            <tr>  
                 <th width="40%">Product Name</th>  
                 <th width="10%">Quantity</th>  
                 <th width="20%">Price</th>  
                 <th width="15%">Total</th>  
                 <th width="5%">Action</th>  
            </tr>  
            <?php   
            if(!empty($_SESSION['shopping_cart'])):  

                 $total = 0;  

                 foreach($_SESSION['shopping_cart'] as $key => $product): 
            ?>  
            <tr>  
               <td><?php echo $product['name']; ?></td>  
               <td><?php echo $product['quantity']; ?></td>  
               <td>$ <?php echo $product['price']; ?></td>  
               <td>$ <?php echo number_format($product['quantity'] * $product['price'], 2); ?></td>  
               <td>
                   <form method="post">
                       <input class="delete" type="submit" name="delete" value="Delete">
                       <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                   </form>
               </td>  
            </tr>  
            <?php  
                      $total = $total + ($product['quantity'] * $product['price']);  
                 endforeach;  
            ?>  
            <tr>  
                 <td colspan="3" align="right">Total</td>  
                 <td align="right">$ <?php echo number_format($total, 2); ?></td>

                 <td></td>  
            </tr>  
            <tr>
                <!-- Show checkout button only if the shopping cart is not empty -->
                <td colspan="5">
                 <?php 
                    if (isset($_SESSION['shopping_cart'])):
                    if (count($_SESSION['shopping_cart']) > 0):
                 ?>
                    <a href="checkout.php" class="button">Checkout</a>
                 <?php endif; endif; ?>
                </td>
            </tr>
            <?php  
            endif;
            ?>  
            </table>   
    </div>
    </div>

Container.php

<?php
                while ($row = mysqli_fetch_assoc($item)) {
        ?>
                    <div class='item-box'>
                    <img class='item_img' src="itemimg/<?php echo $row['img']; ?>"><figcaption><?php echo $row['title']; ?></ficgcaption>
                    <form method="post" class="add-form">
                    <div class='input-group xs-2'>
                        <input class="form-control" type="text" id="quantity<?php echo $row['id'] ?>" name="quantity" value="1">
                        <input class="btn btn-outline-primary btn-sm add-btns add_to_cart" type="submit" id="<?php echo $row['id'] ?>" name="add_to_cart" value="Add To Cart">
                    </div>
                    <input type="hidden" id="name<?php echo $row['id'] ?>" name="name" value="<?php echo $row['title'] ?>">
                    <input type="hidden" id="price<?php echo $row['id'] ?>" name="price" value="<?php echo $row['price']; ?>">
                    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                    </div>

                    </form>
        <?php
                }

        ?>

1 个答案:

答案 0 :(得分:0)

您的页面将刷新,因为您没有告诉您的表单没有通过默认方法提交(即将页面重新加载为POST)。要阻止页面重新加载并让ajax执行提交,您需要注入事件然后使用preventDefault()

$(document).on('click', '.add_to_cart', function(e){
    // This will stop the form from submitting and allow the rest of the 
    // ajax to continue working. If you don't have this, you will immediately
    // submit the form which negates the use of ajax
    e.preventDefault();