Javascript 向我的购物车添加项目时Ajax出现问题

Javascript 向我的购物车添加项目时Ajax出现问题,javascript,php,jquery,ajax,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

我刚刚开始学习如何编程,在将项目添加到购物车时,我一直遇到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>

$(文档).ready(函数(){
$(文档)。在('单击','上。将'添加到'购物车',函数(){
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();
如果(产品数量>0)
{
$.ajax({
url:“index.php”,
方法:“张贴”,
数据:{产品标识:产品标识,产品名称:产品名称,产品价格:产品价格,产品数量:产品数量},
成功:功能(数据)
{
警报(“商品已添加到购物车中”);
}
});
}
其他的
{
警报(“租赁输入数量”);
}
});
});
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']);
    }

    ?>

您的页面将刷新,因为您没有告诉表单不要使用默认方法提交(即以
POST
的形式重新加载页面)。要停止重新加载页面并让ajax进行提交,需要插入事件,然后使用
preventDefault()


您可以添加项,但ajax不起作用?但是ajax是将项目添加到购物车的人
<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>
<?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
                }

        ?>
$(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();