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';
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;
}
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;
}
?>
// 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);
}
});
}
});
// 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>
<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
<pre>session_start();
echo count($_SESSION['cart']);
exit;
?>