Hi Team
I have this issue while debugging on the console tab, its says failed to fetch cart and update cart and causes server receives invalid json data. How can i solve this problem? Is it because what is on the html or cart table should be the same?
What I have tried:
<pre><?php
$dsn = 'mysql:host=localhost;dbname=ecommerce_store';
$username = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = json_decode(file_get_contents('php://input'), true);
if (is_array($data)) {
foreach ($data as $item) {
$id = $item['id'];
$quantity = $item['quantity'];
$stmt = $pdo->prepare("UPDATE cart SET quantity = :quantity WHERE id = :id");
$stmt->bindParam(':quantity', $quantity);
$stmt->bindParam(':id', $id);
$stmt->execute();
}
$response = ['success' => true];
echo json_encode($response);
} else {
$response = ['error' => 'Invalid JSON data'];
echo json_encode($response);
}
} catch (PDOException $e) {
$response = ['error' => 'Database connection error: ' . $e->getMessage()];
echo json_encode($response);
}
?>
// html code
<div class="col-lg-3 col-6 text-right">
<a href="#" class="btn border">
class="fas fa-shopping-cart text-primary">
0
</a>
</div>
<pre> <div class="col-lg-4 col-md-6 col-sm-12 pb-1">
<div class="card product-item border-0 mb-4" id="productId">
<div class="card-header product-img position-relative overflow-hidden bg-transparent border p-0">
<img class="img-fluid w-100" src="img/product-1.jpg" alt="" id="product_img">
</div>
<div class="card-body border-left border-right text-center p-0 pt-4 pb-3">
<h6 class="text-truncate mb-3" id="product_name">Colorful Stylish Shirt 0</h6>
<div class="d-flex justify-content-center">
<h6>R120.00</h6><h6 class="text-muted ml-2" id="price"><del>R120.00</del></h6>
</div>
</div>
<div class="card-footer d-flex justify-content-between bg-light border">
<a href="#" class="btn btn-sm text-dark p-0 view-details-btn" id="cart-0">View Detail</a>
<a href="#" class="btn btn-sm text-dark p-0 add-to-cart-btn" id="add_to_cart-1">
^__i class="fas fa-shopping-cart text-primary mr-1">Add To Cart</a>
</div>
</div>
</div>
// jquery code
<pre lang="Javascript">$(document).ready(function() {
fetchCart();
$('.add-to-cart-btn').click(function(e) {
e.preventDefault();
var productId = $(this).attr('id').split('-')[1];
addToCart(productId);
});
$('.cart-quantity').change(function() {
var productId = $(this).attr('data-productId');
var quantity = $(this).val();
updateCart(productId, quantity);
});
function fetchCart() {
$.ajax({
url: 'fetch-cart.php',
type: 'GET',
dataType: 'json',
success: function(response) {
if (response && response.success) {
renderCart(response.cart);
} else {
console.error('Failed to fetch cart');
}
},
error: function() {
console.error('Failed to fetch cart');
}
});
}
function renderCart(cart) {
var cartItems = '';
var totalQuantity = 0;
var totalPrice = 0;
$.each(cart, function(index, item) {
var rowTotal = item.price * item.quantity;
cartItems += `
<tr>
<td>${item.product_name}</td>
<td>${item.price}</td>
<td>
<input type="number" class="cart-quantity" data-productId="${item.id}" value="${item.quantity}" min="1">
</td>
<td>${rowTotal}</td>
</tr>
`;
totalQuantity += parseInt(item.quantity);
totalPrice += rowTotal;
});
$('.badge123').text(totalQuantity);
$('#cart-table tbody').html(cartItems);
$('#total-quantity').text(totalQuantity);
$('#total-price').text(totalPrice);
}
function addToCart(productId) {
$.ajax({
url: 'update-cart.php',
type: 'POST',
dataType: 'json',
data: { id: productId, quantity: 1 },
success: function(response) {
if (response && response.success) {
fetchCart();
console.log('Cart updated');
} else {
console.error('Failed to update cart');
}
},
error: function() {
console.error('Failed to update cart');
}
});
}
function updateCart(productId, quantity) {
$.ajax({
url: 'update-cart.php',
type: 'POST',
dataType: 'json',
data: { id: productId, quantity: quantity },
success: function(response) {
if (response && response.success) {
fetchCart();
console.log('Cart updated');
} else {
console.error('Failed to update cart');
}
},
error: function() {
console.error('Failed to update cart');
}
});
}
});