繁体   English   中英

将商品添加到购物车PHP时Ajax出现问题

[英]Problems with Ajax when adding items to my shopping Cart PHP

我刚刚开始学习如何编程,并且在向购物车中添加商品时遇到了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
                }

        ?>

您的页面将刷新,因为您没有通过默认方法(即以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();

暂无
暂无

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

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