Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Team

I have a shopping cart shows an item when its add or decrease, but when i refresh my page it only holds 1 item to the basket. There are no errors on the browser when inspecting. What could i be missing to my count?

What I have tried:

<?php
session_start();

var_dump($_SESSION['cart']);

require_once 'dbconn.php';

// add to cart
if(isset($_POST['id'])) {
  $product_id = $_POST['id'];
  if(isset($_SESSION['cart'][$product_id])) {
    $_SESSION['cart'][$product_id]++;
  } else {
    $_SESSION['cart'][$product_id] = 1;
  }
  echo count($_SESSION['cart']);
  exit;
}

// update cart
if(isset($_POST['update_cart'])) {
  $cart_data = $_POST['cart_data'];
  foreach($cart_data as $product_id => $quantity) {
    $_SESSION['cart'][$product_id] = $quantity;
  }
  echo 'success';
  exit;
}

?>
PHP



// jquery
$(document).ready(function() {
    update_cart_count();

    $('.add-to-cart-btn').click(function() {
        var product_id = $(this).data('id');

        $.ajax({
            url: 'add_to_cart.php',
            method: 'POST',
            data: {
                id: product_id
            },
            success: function(response) {
                update_cart_count();
            }
        });
    });

    function update_cart_count() {
        $.ajax({
            url: 'cart_count.php',
            method: 'GET',
            success: function(response) {
                $('#cart-count').html(response);
            }
        });
    }
});
JavaScript



// html code

<div id="basket-overview" class="navbar-collapse collapse d-none d-lg-block">
            <a href="basket.html" class="btn btn-primary navbar-btn">
            class="fa fa-shopping-cart">
           <span id="cart-count"><?php echo count($_SESSION['cart']); ?></span>
           </a>
          </div>
HTML



  <td><a href="#"><img src="img/detailsquare.jpg" alt="White Blouse Armani"></a></td>
  <td><a href="#">White Blouse Armani</a></td>
  <td>
    <div class="input-group">
      
        <button class="btn btn-default btn-minus" type="button">-</button>
      
      <input type="number" name="product1" value="2" min="1" class="form-control product-quantity" data-product-id="1">
      
        <button class="btn btn-default btn-plus" type="button">+</button>
      
    </div>
  </td>
  <td>R50</td>
  <td>%13</td>
  <td>R40</td>
  <td><a href="#">class="fa fa-trash-o"></a></td>
</tr>


// cart_count.php
PHP
<pre>session_start();
echo count($_SESSION['cart']);
exit;
?>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900