Guest User

Guest User

  • Tech Writer
  • 2.1k
  • 472.4k

Calculating total in shopping cart shows Nan

Apr 24 2023 4:57 AM

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
<?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;
}

?>




// 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('', '').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();
});



// 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 ><img src="img/detailsquare.jpg" alt="White Blouse Armani"></a></td>
                          <td><a >White Blouse Armani</a></td>
                          <td>
                <div class="input-group">
                <span class="input-group-btn">
                <button class="btn btn-default btn-minus" type="button">-</button>
                </span>
                <input type="number" name="product1" value="0" min="1" class="form-control product-quantity" data-product-id="1">
              <span class="input-group-btn">
              <button class="btn btn-default btn-plus" type="button">+</button>
            </span>
          </div>
                          </td>
                          <td>R</td>
                          <td></td>
                          <td>R</td>
                          <td><a "><i class="fa fa-trash-o"></i></a></td>
                        </tr>
                        <tr>
  <td><a"><img src="img/detailsquare.jpg" alt="White Blouse Armani"></a></td>
  <td><a >White Blouse Armani</a></td>
  <td>
    <div class="input-group">
      <span class="input-group-btn">
        <button class="btn btn-default btn-minus" type="button">-</button>
      </span>
      <input type="number" name="product1" value="0" min="1" class="form-control product-quantity" data-product-id="1">
      <span class="input-group-btn">
        <button class="btn btn-default btn-plus" type="button">+</button>
      </span>
    </div>
  </td>
  <td>R</td>
  <td>%13</td>
  <td>R</td>
  <td><a ><i class="fa fa-trash-o"></i></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"></i> Continue shopping</a></div>
                    <div class="right">
                      <button id="add-to-cart-btn" class="btn btn-outline-secondary"><i class="fa fa-refresh"></i> Update cart</button>
                      <button class="btn btn-primary" type="submit" >Proceed to checkout <i class="fa fa-chevron-right"></i></button>
                    </div>
                  </div>
                </form>
              </div>

 


Answers (3)