Click here to Skip to main content
15,849,907 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need some help, the problem i am facing when add to cart is called it must show that item to cart. The logic i have so far its not showing that meaning when i add to cart it not displaying that item to be added.

What I have tried:

HTML
<pre><a href="" class="btn border">
                    
     <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">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">Add To Cart</a>

                    </div>

JavaScript
<pre>$(document).ready(function() {
    // Add to cart button click event
    $(document).on('click', '.add-to-cart-btn', 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">×</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();
  });
}

});


PHP
<pre><?php
session_start();

$dbHost = 'localhost';
$dbName = 'ecommerce_store';
$dbUser = 'root';
$dbPass = '';

try {
  $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
  exit;
}

if (isset($_POST['email']) && isset($_POST['password'])) {
  $email = $_POST['email'];
  $password = $_POST['password'];

  $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
  $stmt->execute(['email' => $email]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);

  if ($user && password_verify($password, $user['password'])) {
    // valid credentials, store user session
    $_SESSION['user'] = $user;
    $_SESSION['logged_in'] = true; // set logged_in to true
    header("Location: shopping.php");
    exit();
  } else {
    // invalid credentials
    echo "failure";
  }
}
?>


PHP
<pre><?php
session_start();
require_once 'dbconn.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $itemId = $_POST['itemId'];

    // Check if the user is logged in
    if (isset($_SESSION['id'])) {
        $userId = $_SESSION['id'];

        // Add the item to the cart in the database
        $query = "INSERT INTO cart (id, product_name) VALUES (:id, :product_name)";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $userId);
        $stmt->bindParam(':product_name', $product_name);
        $stmt->execute();

        // Return a success response with the updated cart item count
        $cartItemCount = getCartItemCount($db, $userId);
        $response = array(
            'status' => 'success',
            'cartItemCount' => $cartItemCount
        );
    } else {
        // User is not logged in
        $response = array('status' => 'login_required');
    }

    // Send the JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
}
    // Function to get the count of items in the cart for a specific user
function getCartItemCount($db, $userId) {
    $query = "SELECT COUNT(*) FROM cart WHERE id = :id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':id', $userId);
    $stmt->execute();
    return $stmt->fetchColumn();
}

?>
Posted
Updated 4-Jul-23 0:56am

1 solution

The item will never show in your cart as you are checking if the user is logged in, if so, then add item to cart. You have however set the 'isLoggedIn' value to false which means that the function to update your cart will always be false as per your code -
PHP
var isLoggedIn = false; // Set this value based on your authentication logic

//Here you set isLoggedIn to false which means that you are calling your showLoginOrRegisterPrompt(itemId) function and not the addToCart(itemId) function...

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


You need to change your code to do a proper check whether user is logged in or not and based on that return make a call to your functions.
 
Share this answer
 
v2
Comments
Gcobani Mkontwana 4-Jul-23 6:56am    
@Andre Oosthuizen thanks for the clarity will amend the code and make necessary changes.
Andre Oosthuizen 4-Jul-23 7:51am    
Pleasure

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