Hi Team
I need some help with add to cart, its not updating but i get failed to add to cart on client side. On the server side, i am getting invalid json data. What am missing from my logic by looking at the front end side?
// html code
Colorful Stylish Shirt 0
R120.00
R120.00
// jquery code
$(document).ready(function() {
// Fetch and display the cart
fetchCart();
// Add event listener to the "Add To Cart" button
$('.add-to-cart-btn').click(function(e) {
e.preventDefault();
var productId = $(this).attr('id').split('-')[1];
addToCart(productId);
});
// Update the cart on quantity change
$('.cart-quantity').change(function() {
var productId = $(this).attr('data-productId');
var quantity = $(this).val();
updateCart(productId, quantity);
});
// Fetch the cart from the server
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');
}
});
}
// Render the cart on the page
function renderCart(cart) {
var cartItems = '';
var totalQuantity = 0;
var totalPrice = 0;
$.each(cart, function(index, item) {
var rowTotal = item.price * item.quantity;
cartItems += `
${item.product_name}
${item.price}
${rowTotal}
`;
totalQuantity += parseInt(item.quantity);
totalPrice += rowTotal;
});
// Update the cart badge
$('.badge123').text(totalQuantity);
// Update the cart table body
$('#cart-table tbody').html(cartItems);
// Update the total quantity and price
$('#total-quantity').text(totalQuantity);
$('#total-price').text(totalPrice);
}
// Add a product to the cart
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');
}
});
}
// Update the quantity of a product in the cart
function updateCart(productId, quantity) {
const cartProps = JSON.stringify({id: productId, quantity: quantity });
$.ajax({
url: 'update-cart.php',
type: 'POST',
dataType: 'json',
data: cartProps,
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');
}
});
}
});
// php code
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Retrieve the JSON data from the request
$data = json_decode(file_get_contents('php://input'), true);
// Perform the necessary operations to update the cart in the database
if (is_array($data)) {
foreach ($data as $item) {
$id = $item['id'];
$quantity = $item['quantity'];
// Update the cart item quantity in the database
$stmt = $pdo->prepare("UPDATE cart SET quantity = :quantity WHERE id = :id");
$stmt->bindParam(':quantity', $quantity);
$stmt->bindParam(':id', $id);
$stmt->execute();
}
// Return a success response
$response = ['success' => true];
echo json_encode($response);
} else {
// Return an error response if the JSON data is invalid
$response = ['error' => 'Invalid JSON data'];
echo json_encode($response);
}
} catch (PDOException $e) {
// Return an error response if there's a database connection issue
$response = ['error' => 'Database connection error: ' . $e->getMessage()];
echo json_encode($response);
}
?>
Rajkiran SwainPosted May 17, 2023, 10:54 AM
Based on the provided code, it seems that the issue lies in the JSON data being sent to the server. The server is expecting an array of objects, but the data being sent is not formatted correctly. Here are a few things you can check to resolve the issue:
Check the JSON data: Make sure that the data being sent in the
cartPropsvariable is in the correct format. It should be an array of objects, where each object represents a cart item withidandquantityproperties.Ensure proper JSON serialization: Use
JSON.stringify()to properly serialize thecartPropsobject before sending it in the AJAX request. Update theupdateCartfunction as follows:json_decode()to convert the JSON string back into an array of objects. Update the PHP code as follows:By ensuring that the JSON data is properly formatted and handling it correctly on the server side, you should be able to resolve the issue of receiving an "Invalid JSON data" error.