Wishlist items are not added nor updating when invoke using button to add

Hi Team

I need some help, i have wishlist and what i want to achieve when i click the button to add item from the wishlist must update item and display, then following it open up modal form for users to login. Currently its not getting at this point, but when i debug server side and client side get same message “User is not logged in”, this happends after invoked the button to add an item. What am doing wrong, please correct me, thank you.

// html code

<a href="#" class="btn border" id="cart-badge-btn">
            <i class="fas fa-heart text-danger"></i>
            <span class="badge" id="wishlist-badge">0</span>
            </a>
<!-- Modal login for users adding wishlist -->
<div class="modal fade" id="wishlistLoginModal" tabindex="-1" role="dialog" aria-labelledby="wishlistLoginModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="wishlistLoginModalLabel">Login to View Wishlist</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="loginForm" action="get-wishlist-product.php" method="POST">
                    <div class="form-group">
                        <label for="username">Username</label>
                        <input type="text" class="form-control" id="username" name="username" placeholder="Enter your username " required>
                    </div>
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input type="password" class="form-control" id="password" name="password" placeholder="Enter your password" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Login</button>
                </form>
                <div id="wishlistContent">
                    <!-- Wishlist items will be displayed here after successful login -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

// js code
/***
@author:Gcobani Mkontwana
@date:11/10/2023
@script handles adding of wishlist to cart.

**/
$(document).ready(function () {
    // Initialize wishlist count to 0
    let wishlistCount = 0;

    // Function to update the wishlist badge count
    function updateWishlistBadge() {
        $("#wishlist-badge").text(wishlistCount);
    }

    // Function to open the login modal when the badge is clicked
    function openLoginModal() {
        $("#wishlistLoginModal").modal("show");
    }

    // Function to display wishlist items
    function displayWishlistItems() {
        // Here, you should make an AJAX request to your server to fetch the user's wishlist items.
        // Replace the following code with your actual request:
        $.ajax({
            url: 'get-wishlist-product.php', // Replace with your API endpoint
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    // The server should return an array of wishlist items.
                    const wishlistItems = response.items;

                    // Clear the existing items in the list
                    $('#wishlistItems').empty();

                    // Add each item to the list
                    wishlistItems.forEach(function (item) {
                        $('#wishlistItems').append(`<li class="list-group-item">${item.product_name}</li>`);
                    });
                }
            },
            error: function (error) {
                console.error('Error fetching wishlist items:', error);
            }
        });
    }

    // Listen for the "Add to Wishlist" button click
    $(".add-to-wishlist").click(function () {
        // Simulate adding an item to the wishlist
        const productID = $(this).data("id");
        const productName = $(this).data("product-name");
        const productImage = $(this).data("product-image");

        // You can now send this product information to the server using an AJAX request to add it to the user's wishlist.
        // Replace the following code with your actual request:
        $.ajax({
            url: 'add-to-wishlist.php', // Replace with your API endpoint
            method: 'POST',
            data: { product_id: productID, product_name: productName, product_image: productImage },
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    // If the product is successfully added to the wishlist, update the badge count
                    wishlistCount++;
                    updateWishlistBadge();

                    // If items are in the wishlist, open the login modal and display items
                    if (wishlistCount > 0) {
                        displayWishlistItems();
                        openLoginModal();
                    }
                } else {
                    console.error('Failed to add to wishlist:', response.message);
                }
            },
            error: function (error) {
                console.error('Error adding to wishlist:', error);
            }
        });
    });
});

// server side

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start(); // Start the session to access user data

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
    $product_name = $_POST['product_name'];
    $product_image = $_POST['product_image'];
    $product_code = $_POST['product_code'];

    // Establish a database connection
    $pdo = new PDO("mysql:host=localhost;dbname=database;charset=utf8", "username", "password");

    // Check if the product exists in the products table based on name, image, and code
    $productQuery = "SELECT id FROM products WHERE product_name = :product_name AND product_image = :product_image AND product_code = :product_code";
    $productStmt = $pdo->prepare($productQuery);
    $productStmt->bindParam(":product_name", $product_name, PDO::PARAM_STR);
    $productStmt->bindParam(":product_image", $product_image, PDO::PARAM_STR);
    $productStmt->bindParam(":product_code", $product_code, PDO::PARAM_STR);
    $productStmt->execute();

    if ($productStmt->fetch()) {
        // The product exists, so it's safe to add it to the wishlist
        $query = "INSERT INTO wishlist (user_id, product_name, product_image, product_code) VALUES (:user_id, :product_name, :product_image, :product_code)";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(":user_id", $user_id, PDO::PARAM_INT);
        $stmt->bindParam(":product_name", $product_name, PDO::PARAM_STR);
        $stmt->bindParam(":product_image", $product_image, PDO::PARAM_STR);
        $stmt->bindParam(":product_code", $product_code, PDO::PARAM_STR);
        $stmt->execute();

        $response = array("success" => true, "message" => "Product added to your wishlist.");
    } else {
        $response = array("success" => false, "message" => "Product does not exist.");
    }
} else {
    $response = array("success" => false, "message" => "User is not logged in.");
}

// Return a JSON response
header("Content-Type: application/json");
echo json_encode($response);
?>

So where’s your code that logs a user in?

1 Like

html code

<!-- Modal login for users adding wishlist -->
<div class="modal fade" id="wishlistLoginModal" tabindex="-1" role="dialog" aria-labelledby="wishlistLoginModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="wishlistLoginModalLabel">Login to View Wishlist</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="loginForm" action="get-wishlist-product.php" method="POST">
                    <div class="form-group">
                        <label for="username">Username</label>
                        <input type="text" class="form-control" id="username" name="username" placeholder="Enter your username " required>
                    </div>
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input type="password" class="form-control" id="password" name="password" placeholder="Enter your password" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Login</button>
                </form>
                <div id="wishlistContent">
                    <!-- Wishlist items will be displayed here after successful login -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

javascript code

$(document).ready(function () {
    // Initialize wishlist count to 0
    let wishlistCount = 0;

    // Function to update the wishlist badge count
    function updateWishlistBadge() {
        $("#wishlist-badge").text(wishlistCount);
    }

    // Function to open the login modal when the badge is clicked
    function openLoginModal() {
        $("#wishlistLoginModal").modal("show");
    }

    // Function to display wishlist items
    function displayWishlistItems() {
        // Here, you should make an AJAX request to your server to fetch the user's wishlist items.
        // Replace the following code with your actual request:
        $.ajax({
            url: 'get-wishlist-product.php', // Replace with your API endpoint
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    // The server should return an array of wishlist items.
                    const wishlistItems = response.items;

                    // Clear the existing items in the list
                    $('#wishlistItems').empty();

                    // Add each item to the list
                    wishlistItems.forEach(function (item) {
                        $('#wishlistItems').append(`<li class="list-group-item">${item.product_name}</li>`);
                    });
                }
            },
            error: function (error) {
                console.error('Error fetching wishlist items:', error);
            }
        });
    }

    // Listen for the "Add to Wishlist" button click
    $(".add-to-wishlist").click(function () {
        // Simulate adding an item to the wishlist
        const productID = $(this).data("id");
        const productName = $(this).data("product-name");
        const productImage = $(this).data("product-image");

        // You can now send this product information to the server using an AJAX request to add it to the user's wishlist.
        // Replace the following code with your actual request:
        $.ajax({
            url: 'add-to-wishlist.php', // 
            method: 'POST',
            data: { product_id: productID, product_name: productName, product_image: productImage },
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    // If the product is successfully added to the wishlist, update the badge count
                    wishlistCount++;
                    updateWishlistBadge();

                    // If items are in the wishlist, open the login modal and display items
                    if (wishlistCount > 0) {
                        displayWishlistItems();
                        openLoginModal();
                    }
                } else {
                    console.error('Failed to add to wishlist:', response.message);
                }
            },
            error: function (error) {
                console.error('Error adding to wishlist:', error);
            }
        });
    });
});

The message “User is not logged in” appears in the else clause of this statement:

if (isset($_SESSION['user_id'])) {

so I think what @m_hutley was asking to see was the code where you process your login, to make sure that session variable is being set correctly. I can see the html code for your login form, but there doesn’t seem to be any code in your PHP to take the username and password, check that the user is registered and the password is correct, and set that session variable. All the PHP code you posted does is take the product details and user id, check the product details, and then insert them into the wishlist.

Slightly off-topic, I think it’s unusual to use the product code, image and name to check that the product exists, wouldn’t the product code be sufficient for that? It’s also unusual to store the name, image and code in the wishlist - again, wouldn’t the code be sufficient for that? Why duplicate that information?

I can’t help thinking that it would be better to link the two tables together so that the product_code column in the wishlist is linked to the product_code in the products table, and handle the error that occurs if you try to insert a product into the wishlist that doesn’t exist in the products table.

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