繁体   English   中英

如何在不刷新页面的情况下执行删除到购物车和更新购物车

[英]How can I perform remove to cart and update cart without page refresh

我有一个简单的代码来将项目添加到购物车,当用户删除项目购物车页面刷新并使其滚动回顶部。 更新数量也一样。 我相信我可以让这些功能在没有页面刷新的情况下工作,但我不知道如何执行它。 这是我的购物车代码

<?php 
session_start();

// check if the delete_id is passed via the URL
if(isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    // search for the product to delete
    foreach($_SESSION['cart'] as $key => $product) {
        if($product['id'] === $delete_id) {
            unset($_SESSION['cart'][$key]);
        }
    }
}

// check if the update_id and quantity are passed via the URL
if(isset($_GET['update_id']) && isset($_GET['quantity'])) {
    $update_id = (int)$_GET['update_id'];
    $quantity = (int)$_GET['quantity'];
    // search for the product to update
    foreach($_SESSION['cart'] as $key => $product) {
        if($product['id'] === $update_id) {
            if(isset($product['quantity'])) {
                $_SESSION['cart'][$key]['quantity'] = $quantity;
            } else {
                $_SESSION['cart'][$key]['quantity'] = 1;
            }
        }
    }
}

?>
<!DOCTYPE html>
<html>
<head>
  <title>Cart</title>
</head>
<body>
  <!-- Header menu with logo, about us, and cart menu -->
  <div id="header">
    <div id="logo">Logo</div>
    <div id="test">
    <a href="test.php">products Page</a>
    </div>
    <div id="about-us">About Us</div>
    <div id="cart-menu">      
      <a href="cart.php">Cart (<?=count($_SESSION['cart'])?>)</a>
    </div>
  </div>

  <!-- Cart list -->
  <div id="cart-list">
    <?php 
    if (empty($_SESSION['cart'])) {
        echo '<p>Your cart is empty</p>';
    } else {
        $total = 0;
        foreach($_SESSION['cart'] as $product) {
            echo $product['name']. " <br>";
            echo '<button type="button" onclick="decrementQuantity('.$product['id'].')">-</button>';
            echo '<span id="product-'.$product['id'].'-quantity">'.(isset($product['quantity']) ? $product['quantity'] : 1).'</span>';
            echo '<button type="button" onclick="incrementQuantity('.$product['id'].')">+</button>';            
            $subtotal = $product['price'] * (isset($product['quantity']) ? $product['quantity'] : 1);
            echo '<p>Subtotal: $<span id="product-'.$product['id'].'-subtotal">'.number_format($subtotal,2).'</span></p>';
            $total += $subtotal;
            echo '<p><button type="button" onclick="removeFromCart('.$product['id'].')">Remove Item from Cart</button></p>';
            echo '<hr>';
            }
            echo '<p>Total: $<span id="total">'.number_format($total,2).'</span></p>';
            }
            ?>
          </div>
          <script>
          function incrementQuantity(id) {
            var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
            var newQuantity = currentQuantity + 1;
            updateQuantity(id, newQuantity);
          }
          function decrementQuantity(id) {
            var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
            if(currentQuantity > 1) {
                var newQuantity = currentQuantity - 1;
                updateQuantity(id, newQuantity);
            }
          }
          function updateQuantity(id, value) {
            var url = "cart.php?update_id=" + id + "&quantity=" + value;
            // Change the displayed quantity
            document.getElementById('product-' + id + '-quantity').innerHTML = value;
            // Update the subtotal
            var price = parseFloat(document.getElementById('product-' + id + '-subtotal').innerHTML) / parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
            document.getElementById('product-' + id + '-subtotal').innerHTML = price * value;
            updateTotal();
            window.location.href = url;
          }
          function removeFromCart(id) {
            var url = "cart.php?delete_id=" + id;
            window.location.href = url;
          }
          function updateTotal() {
            var total = 0;
            var subtotals = document.getElementsByClassName('product-subtotal');
            for (var i = 0; i < subtotals.length; i++) {
                total += parseFloat(subtotals[i].innerHTML);
            }
            document.getElementById('total').innerHTML = total;
          }
          </script>
        </body>
        </html>

我读到的是我应该向按钮添加事件侦听器并使用 $.ajax() 方法...我的编码不太好因此我无法实现它所以我什至不知道它是否会起作用

<?php 
session_start();
// check if the delete_id is passed via the URL
if(isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    // search for the product to delete
    foreach($_SESSION['cart'] as $key => $product) {
        if($product['id'] === $delete_id) {
            unset($_SESSION['cart'][$key]);
            echo "success";die;
        }
    }
}

// check if the update_id and quantity are passed via the URL
if(isset($_GET['update_id']) && isset($_GET['quantity'])) {
    $update_id = (int)$_GET['update_id'];
    $quantity = (int)$_GET['quantity'];
    // search for the product to update
    foreach($_SESSION['cart'] as $key => $product) {
        if($product['id'] === $update_id) {
            if(isset($product['quantity'])) {
                $_SESSION['cart'][$key]['quantity'] = $quantity;
            } else {
                $_SESSION['cart'][$key]['quantity'] = 1;
            }
            echo "success";die;
        }
    }
}

?>
<!DOCTYPE html>
<html>
<head>
  <title>Cart</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
    <div id="header">
        <div id="logo">Logo</div>
        <div id="test">
            <a href="test.php">products Page</a>
        </div>
        <div id="about-us">About Us</div>
        <div id="cart-menu">      
            <a href="cart.php">Cart (<?=count($_SESSION['cart'])?>)</a>
        </div>
    </div>
    <!-- Cart list -->
    <div id="cart-list">
        <?php 
        if (empty($_SESSION['cart'])) {
            echo '<p>Your cart is empty</p>';
        } else {
            $total = 0;
            foreach($_SESSION['cart'] as $product) {
                echo "<div class='product product-".$product['id']."'>";
                echo $product['name']. " <br>";
                echo '<input type="hidden" id="product-'.$product['id'].'-price" value="'.$product['price'].'">';
                echo '<button type="button" onclick="decrementQuantity('.$product['id'].')">-</button>';
                echo '<span id="product-'.$product['id'].'-quantity">'.(isset($product['quantity']) ? $product['quantity'] : 1).'</span>';
                echo '<button type="button" onclick="incrementQuantity('.$product['id'].')">+</button>';            
                $subtotal = $product['price'] * (isset($product['quantity']) ? $product['quantity'] : 1);
                echo '<p>Subtotal: $<span id="product-'.$product['id'].'-subtotal" class="subtotals">'.number_format($subtotal,2).'</span></p>';
                $total += $subtotal;
                echo '<p><button type="button" onclick="removeFromCart('.$product['id'].')">Remove Item from Cart</button></p>';
                echo '<hr></div>';
            }
            echo '<p>Total: $<span id="total">'.number_format($total,2).'</span></p>';
        }
        ?>
    </div>
    <script>
        function incrementQuantity(id) {
            var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
            var newQuantity = currentQuantity + 1;
            updateQuantity(id, newQuantity);
        }
        function decrementQuantity(id) {
            var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
            if(currentQuantity > 1) {
                var newQuantity = currentQuantity - 1;
                updateQuantity(id, newQuantity);
            }
        }
        function updateQuantity(id, value) {
            var $proC = $('.product.product-' + id );
            var product_price = $('#product-'+id+'-price').val();
            
            $proC.find('button').attr("disabled","disabled");
            var url = "cart.php?update_id=" + id + "&quantity=" + value;
            
            $.ajax({
                url:url,
                type:'GET',
                success:function(response){
                    $proC.find('button').removeAttr("disabled");
                    if($.trim(response) == 'success'){
                        document.getElementById('product-'+id+'-quantity').innerHTML = value;
                        document.getElementById('product-'+id+'-subtotal').innerHTML = product_price * value;
                    }else{
                        alert("Something went wrong.try again..");
                    }
                    updateTotal();
                },
                error:function(err){
                    $proC.find('button').removeAttr("disabled");
                    alert(err);
                }
            })
        }
        function removeFromCart(id) {
            var url = "cart.php?delete_id=" + id;
            $.ajax({
                url:url,
                type:'GET',
                success:function(response){
                    if($.trim(response) == 'success'){
                        $('.product.product-'+id).remove();
                        alert("Product removed.");
                    }else{
                        alert("Something went wrong.try again..");
                    }
                },
                error:function(err){
                    alert(err);
                }
            })
        }
        function updateTotal() {
            var total = 0;
            var subtotals = document.getElementsByClassName('subtotals');
            for (var i = 0; i < subtotals.length; i++) {
                total += parseFloat(subtotals[i].innerHTML);
            }
            document.getElementById('total').innerHTML = total;
        }
    </script>
</body>
</html>

暂无
暂无

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

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