Guest User

Guest User

  • Tech Writer
  • 2.1k
  • 472.3k

Removing item from the list

Oct 4 2023 2:48 PM

Hi Team

I have cart item and want to remove using button, but when debug i get this error and " Uncaught ReferenceError: removeItemFromCart is not defined".Below is my add-to-cart.js logic and have used delegates but still unlucky.

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

      var productId = $(this).data("id");
      console.log("Product ID:", productId);
      var productName = $(this).data("product-name");
      var productImage = $(this).data("product-image");

      var quantity = parseInt($("#quantity-input").val());
      //store the product ID in the session.
      var productImage = "img/" + productId + ".jpg";

      var productPrice = parseFloat($("#product-price-" + productId).text().replace("R", ""));
      var totalPrice = productPrice * quantity;

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

      sessionStorage.setItem("cartItems", JSON.stringify(cartItems));
    $.ajax({
      type: "POST",
      url: "add-to-cart.php",
      data: { productId: productId },
      success: function(response) {
        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 to update cart items in the modal
function updateCartItems(cartData) {
    var cartItems = cartData.cartItems;
    var cartContainer = $("#cart-items");

    // Clear the previous content
    cartContainer.empty();

    // Loop through the cart items and add them to the HTML
    cartItems.forEach(function (item) {
        var totalPrice = item.totalPrice || 0; // Ensure totalPrice is a valid number or set it to 0
        var cartItemHtml = `
            <tr>
                <td>${item.product_name}</td>
                <td><img src="${item.product_image}" alt="${item.product_name}" class="img-thumbnail"></td>
                <td>R${totalPrice.toFixed(2)}</td>
                <td>${item.quantity}</td>
                <td><button class="btn btn-danger btn-sm" data-productId="${item.product_id}" onclick="removeItemFromCart(${item.product_id})">Remove</button></td>

            </tr>
        `;

        // Append the cart item HTML to the container
        cartContainer.append(cartItemHtml);
    });

    // Update the total price
    var totalPriceContainer = $("#total-price");
    totalPriceContainer.text("Total Price: R" + cartData.totalPrice.toFixed(2));
}

// Use event delegation to handle click events for "Remove" buttons inside the modal
$("#cartModal").on("click", ".remove-cart-item", function () {
    var productId = $(this).data("productId");
    removeItemFromCart(productId);
});

//removing item from cart.
    function removeItemFromCart(productId) {
    $.ajax({
        type: "POST",
        url: "removeCartItem.php",
        data: { productId: productId }, // Include the product ID in the data
        dataType: "json",
        success: function (response) {
            if (response.success) {
                // Item removed successfully, update the cart display
                getCartItemsForModal();
                updateCartItems();
            } else {
                alert(response.message); // Display the error message from the server
            }
        },
        error: function (xhr, status, error) {
            alert("An error occurred while removing the item from the cart.");
            console.log(xhr.responseText);
        },
    });
}

    // 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 get item from the cart.
  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 


<div class="modal fade" id="cartModal" tabindex="-1" role="dialog" aria-labelledby="cartModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cartModalLabel">Cart Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Image</th>
                            <th>Price</th>
                            <th>Quantity</th>
                            <th>Action</th> // remove should work here
                        </tr>
                    </thead>
                    <tbody id="cart-items">
                        <!-- Cart items will be populated here -->
                    </tbody>
                </table>
                <div id="cart-summary"></div> <!-- Move this div inside the modal-body -->
                <p id="total-price">Total Price: R0</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="checkout-btn">View Cart</button>
            </div>
        </div>
    </div>
</div>

 


Answers (3)