Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Team

I am trying to calculate total amount of item added on the basket in my web application using jquery(this is done on this side but not displaying when a user add all items together and discount of an item) and php. When debugging there only thing i see is Nan on the table and need some help.

What I have tried:

// html code
<div id="basket" class="col-lg-9">
              <div class="box">
                <form method="post" action="add_to_cart.php">
                  <h1>Shopping cart</h1>
                  <p class="text-muted">You currently have <span id="cart-count"><?php echo count($_SESSION['cart']); ?></span>
                  <p id="cart-message" class="text-success" style="display: none;"></p>
                  <div class="table-responsive">
                    <table class="table">
                      <thead>
                        <tr>
                          <th colspan="2">Product</th>
                          <th>Quantity</th>
                          <th>Unit price</th>
                          <th>Discount</th>
                          <th colspan="2"><span id="total-amount">Total</span></th>

                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <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="0" min="1" class="form-control product-quantity" data-product-id="1">
              
              <button class="btn btn-default btn-plus" type="button">+</button>
            
          </div>
                          </td>
                          <td>R</td>
                          <td></td>
                          <td>R</td>
                          <td><a href="#">class="fa fa-trash-o" href="#" src="img/detailsquare.jpg" alt="White Blouse Armani" name="product1" data-product-id="1"></a></td>
</tr>

                      </tbody>
                      <tfoot>
                        <tr>
                          <th colspan="5" id="total-amount">Total</th>
                          <th colspan="2"></th>
                          
                        </tr>
                      </tfoot>
                    </table>
                  </div>
                  <p id="cart-message" class="text-success" style="display: none;"></p>
                  <!-- /.table-responsive-->
                  <div class="box-footer d-flex justify-content-between flex-column flex-lg-row">
                    <div class="left"><a href="category.html" class="btn btn-outline-secondary">^__i class="fa fa-chevron-left"> Continue shopping</a></div>
                    <div class="right">
                      <button id="add-to-cart-btn" class="btn btn-outline-secondary">^__i class="fa fa-refresh"> Update cart</button>
                      <button class="btn btn-primary" type="submit" >Proceed to checkout ^__i class="fa fa-chevron-right"></button>
                    </div>
                  </div>
                </form>
              </div>


// 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 = $('<tr>').appendTo($cart_table.find('tbody'));
        $('<td>').append($('<img>').attr('src', 'img/detailsquare.jpg').attr('alt', product.product_name)).appendTo($row);
        $('<td>').append($('<a>').attr('href', '#').text(product.product_name)).appendTo($row);
        $('<td>').text(quantity).appendTo($row);
        $('<td>').text('$' + price.toFixed(2)).appendTo($row);
        $('<td>').text((discount * 100) + '%').appendTo($row);
        $('<td>').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();
});
JavaScript



// php code
PHP
<pre><?php
session_start();


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;
}
$total = $_POST['total'];
echo json_encode(array('success' => true, 'total' => $total));
exit;
}

?>
Posted
Comments
Member 15627495 24-Apr-23 1:54am    
'bill' and 'amount' don't have their places by 'client side'.
It's really risky.

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