Home > front end >  How can I perform remove to cart and update cart without page refresh
How can I perform remove to cart and update cart without page refresh

Time:01-13

i have a simple code to add items to cart, when a user removes items to cart the page refreshes and that makes it scroll back to the top. updating quantity also does the same. I belive i can have these functions work without page refresh but i dont know how to execute this. here is my cart code

<?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>

what i have read is i should add event listeners to the buttons and use $.ajax() method... I am not so good in coding therefore i cant implement this so i dont even know if it will work

CodePudding user response:

<?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" >'.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>
  • Related