Click here to Skip to main content
15,846,571 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have an issue with my cart basket. It is not displaying when I add the items to the cart. When debugging, I get this errror.
"Uncaught TypeError: item.totalPrice is null
    updateCartItems https://splashonline.co.za/js/add-to-cart.js:139
    updateCartItems https://splashonline.co.za/js/add-to-cart.js:132
    <anonymous> https://splashonline.co.za/js/add-to-cart.js:149
    jQuery 2
"

What I have tried:

JavaScript
$(document).ready(function() {
  $(".add-to-cart-btn").click(function(e) {
    e.preventDefault();

    var productId = $(this).data("id");
    var productName = $(this).data("product-name");
    var productImage = $(this).data("product-image");

    // Get quantity from your quantity input element
    var quantity = parseInt($("#quantity-input-" + 
                   productId).val()); // Make sure the ID is correct
    // Get the product price from the data attribute
    var productPrice = parseFloat($(this).data("product-price"));

    // Store the product details in the session
    var cartItems = JSON.parse(sessionStorage.getItem("cartItems")) || [];
    
    cartItems.push({
      productId: productId,
      quantity: quantity,
      productImage: productImage,
      productName: productName,
      totalPrice :totalPrice
    });

    sessionStorage.setItem("cartItems", JSON.stringify(cartItems));

    $.ajax({
      type: "POST",
      url: "add-to-cart.php",
      data: { productId: productId },
      success: function(response) {
        // Debugging: Alert the response to see if it's successful
        alert(response);

        updateCartBadge(); // Update the cart badge with the new count
        getCartItem(); // Refresh the cart items after adding
      },
      error: function(xhr, status, error) {
        alert("An error occurred while adding the item to the cart.");
        console.log(xhr.responseText);
      }
    });
  });
      // Function to update cart badge.
    function updateCartBadge(userId) {
        $.ajax({
            type: "GET",
            url: "getCartItemCount.php",
            data: { userId: userId},
    success: function (response) {
        console.log('Cart Item Count:', response);
        $("#cart-badge").text(response); // Update the cart badge count
    },
    error: function (xhr, status, error) {
        alert("An error occurred while retrieving the cart item count.");
        console.log(xhr.responseText);
    }
});
}

    // function for updating cart items.
    function updateCartItems(cartData) {
        console.log("Response from the server:", cartData);
        var cartItems = cartData.cartItems;
        var cartContainer = document.getElementById("cart-items");
        cartContainer.innerHTML = "";

        cartItems.forEach(function (item) {
            // Create elements to display the cart items
            var itemContainer = document.createElement("tr");

            //column for product-name cart details
            var itemName = document.createElement("td");
            itemName.textContent = item.product_name;
            itemContainer.appendChild(itemName);

            //column for image cart details
            var itemImage = document.createElement("td");
            var image = document.createElement("img");
            image.src = item.product_image;
            image.alt = item.product_name;
            image.classList.add("img-thumbnail");
            itemImage.appendChild(image);
            itemContainer.appendChild(itemImage);

            //column for price cart details
            var itemPrice = document.createElement("td");
            itemPrice.textContent = "$" + item.totalPrice;
            itemContainer.appendChild(itemPrice);

            //column for quantity for cart details.
            var itemQuantity = document.createElement("td");
            itemQuantity.textContent = item.product_qty;
            itemContainer.appendChild(itemQuantity);

            //column for action to remove items.
            var itemAction = document.createElement("td");
            var removeButton = document.createElement("button");
            removeButton.textContent = "Remove";
            removeButton.classList.add("btn", "btn-danger", "btn-sm");
            removeButton.dataset.productId = item.product_id;
            removeButton.addEventListener("click", function () {
                var productId = this.dataset.productId;
                removeItemFromCart(productId);
            });
            itemAction.appendChild(removeButton);
            itemContainer.appendChild(itemAction);

            cartContainer.appendChild(itemContainer);
        });

        var totalPriceContainer = document.getElementById("total-price");
        totalPriceContainer.textContent = "Total Price: R" + cartData.totalPrice;
    }

    // Call the backend to fetch cart data when the cart modal is opened
    $("#cartModal").on("show.bs.modal", function () {
        $.ajax({
            type: "GET",
            url: "getCartData.php",
            dataType: "json",
            success: function (cartData) {
                console.log("Response from the server:", cartData);
                updateCartItems(cartData);
                updateCartBadge();
            },
            error: function (xhr, status, error) {
                alert("An error occurred while fetching cart item details");
                console.log(xhr, responseText);
            }
        });
    });
    
    // function to populate the cart modal with cart items.
    function getCartItemsForModal() {
        $.ajax({
            type: "GET",
            url: "getCartItem.php",
            dataType: "html",
            success: function (response) {
                $("#cart-items").html(response);
            },
            error: function (xhr, status, error) {
                console.log("An error occured while retrieving cart items");
                console.log(xhr.responseText);
            },
        });
    }
    updateCartItems();
    //call getCartItemsForModal function.
    $("#cart-badge-btn").click(function () {
        getCartItemsForModal();
    });

    //function to remove an item from the cart.
    function removeItemFromCart(productId) {
        $.ajax({
            type: "POST",
            url: "removeCartItem.php",
            data: { productId: productId },
            dataType: "json",
            success: function (response) {
                if (response.success) {
                    getCartItemsForModal();
                    updateCartItems();
                } else {
                    alert("An error occured while removing the item from the cart");
                }
            },
            error: function (xhr, status, error) {
                alert("An error occured while removing the item from the cart.");
                console.log(xhr.responseText);
            },
        });
    }

  function getCartItem() {
    $.ajax({
      type: "GET",
      url: "getCartItem.php",
      success: function(response) {
        $("#cart-items").html(response); // Update the cart items on the page
      },
      error: function(xhr, status, error) {
        alert("An error occurred while retrieving the cart items.");
        console.log(xhr.responseText);
      }
    });
  }

  // Call updateCartBadge and getCartItem on page load
  updateCartBadge();
  getCartItem();
});  
});  


// HTML code
HTML
<div class="row px-xl-5 pb-3">
            <div class="col-lg-3 col-md-6 col-sm-12 pb-1">
                <div class="card product-item border-0 mb-4">
                    <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="">
                    </div>
                    <div class="card-body border-left 
                    border-right text-center p-0 pt-4 pb-3">
                        <h6 class="text-truncate mb-3">
                            Colorful Stylish Shirt</h6>
                        <div class="d-flex justify-content-center">
                            <h6>R123.00</h6><
                            h6 class="text-muted ml-2">
                            <del>R123.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 Detail</a>
                        <a href="" class="btn btn-sm text-dark p-0 
                            add-to-cart-btn"
                           data-id="1"
                           data-product-name="Colorful Stylish Shirt"
                           data-product-image="img/product-1.jpg">
                            ^__i class="fas fa-shopping-cart 
                               text-primary mr-1">Add To Cart
                        </a>
                    </div>
                </div>
            </div>






Posted
Updated 3-Oct-23 7:21am
v2
Comments
Graeme_Grant 3-Oct-23 8:31am    
The error message is explicit: "item.totalPrice is null" - ie: your price value is not set, ie, null.

Set a breakpoint where you think that you are setting the price, then when the code pauses, inspect why. This is called "debugging your code".

1 solution

See here: A Beginner’s Guide to JavaScript Debugging in Chrome - CoderPad[^] - there are similar pages for most popular browsers (and probably one for Edge as well).
 
Share this answer
 

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