Hi Team
I am unable to calculate total to my shopping cart and discount, when a user add item on the basket(this shows both incrementing and decrementing). The problem is on getting the discount and total of those item being on the basket. Currently i can only see Nan as total need some help.
// php code
$quantity) {
$_SESSION['cart'][$product_id] = $quantity;
}
$total = $_POST['total'];
echo json_encode(array('success' => true, 'total' => $total));
exit;
}
?>
// jquery code
// Get the cart from local storage
function getCart() {
var cart = localStorage.getItem('cart');
if (cart) {
return JSON.parse(cart);
} else {
return {};
}
}
// Save the cart to local storage
function saveCart(cart) {
localStorage.setItem('cart', JSON.stringify(cart));
}
// Update the cart count in the navbar
function updateCartCount() {
var cartCount = Object.values(getCart()).reduce((a, b) => a + b, 0);
$('#cart-count').text(cartCount);
}
// Add a product to the cart
function addToCart(productId, quantity) {
var cart = getCart();
if (cart.hasOwnProperty(productId)) {
var newQuantity = parseInt(quantity);
if (newQuantity <= 0) {
delete cart[productId];
} else {
cart[productId] = newQuantity;
}
} else {
cart[productId] = parseInt(quantity);
}
saveCart(cart);
updateCartCount();
calculate_total();
// Display message
var productName = $('#product-name-' + productId).text();
$('#cart-message').text(quantity + 'x ' + productName + ' added to cart').show();
setTimeout(function() {
$('#cart-message').fadeOut('slow');
}, 3000);
}
// Calculate and display the total amount in the shopping cart
function calculate_total() {
var cart = getCart();
var total = 0;
for (var productId in cart) {
var product = getProductId(productId);
var price = parseFloat(product.price);
var quantity = parseInt(cart[productId]);
var subtotal = price * quantity * (1 - parseFloat(product.discount));
total += subtotal;
}
$('#total-amount').text('$' + total.toFixed(0)); // update the text of the total td element
$('#total').val(total.toFixed(0));
return total.toFixed(0);
}
// get the product details.
function getProductId(productId) {
return $.ajax({
url: 'get_product_details.php',
data: { productId: productId },
dataType: 'json'
});
}
// display data from the cart.
function display_cart() {
var cart = getCart();
var $cart_table = $('#cart-table');
// Remove existing rows from the table
$cart_table.find('tbody tr').remove();
// Add new rows to the table for each product in the cart
for (var productId in cart) {
$.ajax({
url: 'get-product-details.php',
data: { productId: productId },
success: function(product) {
var price = parseFloat(product.unit_price);
var quantity = parseInt(cart[product.productId]);
var subtotal = price * quantity;
var discount = parseFloat(product.discount);
var total = subtotal - (subtotal * discount);
var $row = $('').appendTo($cart_table.find('tbody'));
$('').append($('
').attr('src', 'img/detailsquare.jpg').attr('alt', product.product_name)).appendTo($row);
$(' ').append($('').attr('', '').text(product.product_name)).appendTo($row);
$(' ').text(quantity).appendTo($row);
$(' ').text('$' + price.toFixed(2)).appendTo($row);
$(' ').text((discount * 100) + '%').appendTo($row);
$(' ').text('$' + total.toFixed(2)).appendTo($row);
},
error: function(xhr, status, error) {
console.error('Error getting product details:', error);
}
});
}
// Update the total amount in the cart
calculate_total();
}
$(document).ready(function() {
$('.btn-plus').click(function() {
var productId = $(this).closest('.input-group').find('.product-quantity').data('product-id');
var quantityInput = $(this).closest('.input-group').find('.product-quantity');
var currentQuantity = parseInt(quantityInput.val());
var newQuantity = currentQuantity + 1;
quantityInput.val(newQuantity);
addToCart(productId, newQuantity);
});
$('.btn-minus').click(function() {
var productId = $(this).closest('.input-group').find('.product-quantity').data('product-id');
var quantityInput = $(this).closest('.input-group').find('.product-quantity');
var currentQuantity = parseInt(quantityInput.val());
if (currentQuantity > 1) {
var newQuantity = currentQuantity - 1;
quantityInput.val(newQuantity);
addToCart(productId, newQuantity);
}
});
// Initialize the cart count in the navbar
updateCartCount();
});
// html code
3 Replies
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Guest UserPosted Apr 24, 2023, 9:30 AM
Hi Amit and Swain, the new code you guys shared is working(data from the table inserted), but to get_product_details.php how can i display this to the shopping cart page? My requirement is to be able to display these data on the same page, question also then be if its a new data being added on the cart, how do i despose this as well?
Amit MohantyPosted Apr 24, 2023, 6:43 AM
Check this
Rajkiran SwainPosted Apr 24, 2023, 6:30 AM