Adding items to cart is not updating them

Hi Team

I have a button add to cart, then server side does the requirement for specific reason of the ecommerce. The problem is add to cart button is not showing any errors but not reading my id element from the cart and need some help.

// html code

<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"><i class="fas fa-eye text-primary mr-1"></i>View Detail</a>
                        <a href="" class="btn btn-sm text-dark p-0 add-to-cart-btn" data-id="1"><i class="fas fa-shopping-cart text-primary mr-1"></i>Add To Cart</a>

                    </div>
                </div>
            </div>

// js file

$(document).ready(function() {
    // Add to cart button click event
    $(document).on('click', '.add-to-cart', function(e) {
        e.preventDefault();
        var itemId = $(this).data('id');

        // Check if the user is logged in
        var isLoggedIn = false; // Set this value based on your authentication logic

        if (isLoggedIn) {
            addToCart(itemId);
        } else {
            showLoginOrRegisterPrompt(itemId);
        }
    });

    // Function to add an item to the cart
function addToCart(itemId) {
  // Send an AJAX request to the server to add the item to the cart
  $.ajax({
    url: 'add_to_cart.php',
    method: 'POST',
    data: { itemId: itemId },
    dataType: 'json',
    success: function(response) {
      if (response.status === 'success') {
        // Item successfully added to the cart
        // You can update the UI to reflect the change, such as updating the cart count
        updateCartCount(response.cartItemCount);
        console.log('Item added to cart.');
      } else if (response.status === 'login_required') {
        // User needs to log in or register to continue
        showLoginOrRegisterPrompt(itemId);
      } else {
        // Error adding item to the cart
        console.log('Error adding item to cart.');
      }
    },
    error: function() {
      console.log('An error occurred while adding item to cart.');
    }
  });
}

    // Function to show the login or register prompt
function showLoginOrRegisterPrompt(itemId) {
  // Create the modal markup
  var modalContent = `
    <div class="modal fade" id="loginRegisterModal" tabindex="-1" role="dialog" aria-labelledby="loginRegisterModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="loginRegisterModalLabel">Login or Register</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <!-- Login and register form here -->
            <form id="loginForm" method="post" action="login.php">
              <h6>Login</h6>
              <div class="form-group">
                <label for="loginEmail">Email</label>
                <input type="email" class="form-control" id="loginEmail" name="loginEmail" required>
              </div>
              <div class="form-group">
                <label for="loginPassword">Password</label>
                <input type="password" class="form-control" id="loginPassword" name="loginPassword" required>
              </div>
              <button type="submit" class="btn btn-primary">Login</button>
            </form>

            <hr>

            <form id="registerForm" method="post" action="register.php">
              <h6>Register</h6>
              <div class="form-group">
                <label for="registerName">Name</label>
                <input type="text" class="form-control" id="registerName" name="registerName" required>
              </div>
              <div class="form-group">
                <label for="registerEmail">Email</label>
                <input type="email" class="form-control" id="registerEmail" name="registerEmail" required>
              </div>
              <div class="form-group">
                <label for="registerPassword">Password</label>
                <input type="password" class="form-control" id="registerPassword" name="registerPassword" required>
              </div>
              <button type="submit" class="btn btn-primary">Register</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  `;

  // Append the modal to the body
  $('body').append(modalContent);

  // Show the modal
  $('#loginRegisterModal').modal('show');

  // Remove the modal from the DOM after it's hidden
  $('#loginRegisterModal').on('hidden.bs.modal', function() {
    $(this).remove();
  });
}


    // Function to update the cart count
    function updateCartCount(cartCount) {
        $('#cart-count').text(cartCount);
    }
});

Where in your markup is there a class add-to-cart?

It appears that there is a discrepancy between the class name used for the add to cart button in your HTML and JavaScript code. In the HTML, the button has the class “add-to-cart-btn,” while in the JavaScript, it is referred to as “.add-to-cart.”

To resolve the issue, ensure that the JavaScript code references the correct class name. Update the JavaScript code to use “.add-to-cart-btn” instead of “.add-to-cart” as the selector for the click event:

javascriptCopy code

$(document).on('click', '.add-to-cart-btn', function(e) {
    // Your code to handle the add to cart functionality
});

By making this adjustment, the JavaScript code will be able to retrieve the data-id attribute from the add to cart button as intended.

@rimshadevrims thank you so much for the support mate, yes my class-name was not corresponding to my js. so after making an adjustment code works fine.

Thats great, I’m happy for you

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.