Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Team

I have client side and my back end is trying to retrieve all the items being added to the wishlist but its returning empty to the table and there are no errors when debugging, i think i might be missing something on my logic and need so help.

What I have tried:

HTML
<pre><!--adding some items to wishlist-->
        <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/wishlist-img/SecondWishlist.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">Golf T-Shirt</h6>
            <div class="d-flex justify-content-center">
                <h6>R200.00</h6>
                <h6 class="text-muted ml-2"><del>R200.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-wishlist-btn" data-product-id="10"
             data-product-name="Golf T-Shirt"
             data-product-code="PROD001"
             data-product-image="img/wishlist-img/SecondWishlist.jpg">
            ^__i class="fas fa-heart text-danger mr-1">Add To Wishlist</a>
        </div>
    </div>
</div>


JavaScript
document.addEventListener('DOMContentLoaded', async function() {
    // Initialize wishlist count and items
    let wishlistCount = 0;
    let wishlistItems = [];

    // Function to update the wishlist badge count
    function updateWishlistBadge() {
        document.getElementById("wishlist-badge").textContent = wishlistCount;
    }

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

    // Function to display wishlist items
    function displayWishlist(wishlistItems) {
        console.log('Received wishlist items:', wishlistItems);
        const wishlistTable = document.getElementById('wishlistTable').getElementsByTagName('tbody')[0];
        wishlistTable.innerHTML = ''; // Clear existing items

        wishlistItems.forEach((item) => {
            console.log('Processing item:', item);
            const row = wishlistTable.insertRow();
            const cell1 = row.insertCell(0);
            const cell2 = row.insertCell(1);
            const cell3 = row.insertCell(2);
            const cell4 = row.insertCell(3);

            cell1.textContent = item.product_name; // Change this to match your data structure
            cell2.innerHTML = `<img src="${item.product_image}" alt="${item.product_name}" class="img-thumbnail">`; // Change this to match your data structure
            cell3.textContent = 'R' + item.product_price.toFixed(2); // Change this to match your data structure
            cell4.textContent = item.quantity; // Change this to match your data structure
        });
    }

    // Load wishlist items and count from the session when the page loads
    wishlistItems = JSON.parse(sessionStorage.getItem('wishlistItems')) || [];
    wishlistCount = parseInt(sessionStorage.getItem('wishlistCount')) || 0;
    updateWishlistBadge();

    // Listen for the "Add to Wishlist" button click
    document.querySelectorAll(".add-to-wishlist-btn").forEach(button => {
        button.addEventListener('click', async function() {
            const productId = this.dataset.productId;
            console.log("Product ID:", productId);
            const productName = this.dataset.productName;
            console.log("Product Name:", productName);
            const productImage = this.dataset.productImage;
            console.log("Product Image", productImage);

            // Simulate adding an item to the wishlist
            wishlistCount++;
            updateWishlistBadge();
            wishlistItems.push({ productId, productName, productImage });
            

            // Store wishlist items and count in session
            sessionStorage.setItem('wishlistItems', JSON.stringify(wishlistItems));
            sessionStorage.setItem('wishlistCount', wishlistCount);
        });
    });

    // Listen for the "Wishlist" badge click
    document.getElementById("wishlist-badge").addEventListener('click', function() {
        console.log("Wishlist badge clicked");
        if (wishlistCount > 0) {
            // Display the login modal
            openLoginModal();
        }
    });

    // When the user logs in successfully, call this function to display wishlist items
    async function onLogin() {
        if (wishlistCount > 0) {
            fetchWishlistItems().then((wishlistItems) => {
             console.log('Received wishlist items:', wishlistItems);
        displayWishlist(wishlistItems);
});
        }
    }

    // Function to fetch wishlist items from the server
    // Function to fetch wishlist items from the server
async function fetchWishlistItems() {
    try {
        const response = await fetch('get-wishlist-items.php', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        });
        console.log('Fetch response:', response);

        if (response.ok) {
            const wishlistItems = await response.json();
            console.log('Received wishlist items:', wishlistItems);
            return wishlistItems;
        } else {
            console.error('Error fetching wishlist items:', response.status);
            return [];
        }
    } catch (error) {
        console.error('Error fetching wishlist items:', error);
        return [];
    }
}

});


PHP
<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);

session_start();

if (isset($_POST['productId'])) {
    $productId = $_POST['productId'];

    // Replace with your database connection details
    $host = 'localhost';
    $dbname = 'testdb';
    $username = 'root';
    $password = 'passwrd';

    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        if (isset($_SESSION['user_id'])) {
            // User is logged in
            $userId = $_SESSION['user_id'];

            // Check if the item already exists in the user's wishlist
            $stmt = $pdo->prepare("SELECT * FROM wishlist WHERE user_id = ? AND product_id = ?");
            $stmt->execute([$userId, $productId]);
            $wishlistItem = $stmt->fetch(PDO::FETCH_ASSOC);
            var_dump($wishlistItem);

            if ($wishlistItem) {
                // Item already exists in the user's wishlist
                echo json_encode(['success' => false, 'message' => 'Item is already in the wishlist.']);
            } else {
                // Fetch product details from the database
                $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
                $stmt->execute([$productId]);
                $product = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($product) {
                    // Item doesn't exist in the user's wishlist, so add it
                    $stmt = $pdo->prepare("INSERT INTO wishlist (user_id, product_id, product_name, product_image, product_price, quantity) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$userId, $productId, $product['product_name'], $product['product_image'], $product['product_price'], 1]);

                    echo json_encode(['success' => true, 'message' => 'Item added to the wishlist.']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Product not found in the database.']);
                }
            }
        } else {
            // User is not logged in
            // Save the item to the session wishlist
            if (!isset($_SESSION['wishlist'])) {
                $_SESSION['wishlist'] = array();
            }

            if (!in_array($productId, $_SESSION['wishlist'])) {
                $_SESSION['wishlist'][] = $productId;
            }

            echo json_encode(['success' => true, 'message' => 'Item added to the wishlist.']);
        }
    } catch (PDOException $e) {
        if ($e->getCode() === '23000') {
             $error_message = 'An error occurred: ' . $e->getMessage();
            
             error_log($error_message);
            // Handle duplicate entry error
            echo json_encode(['success' => false, 'message' => 'Item is already in the wishlist.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
} elseif (isset($_POST['login'])) {
    // This part of the code handles user login
    // You should validate the user's login credentials here

    $username = $_POST['username'];
    $password = $_POST['password'];

    // Perform user authentication here, check if the user exists in the database

    // If the user is successfully authenticated, set their user ID in the session
    // You should replace this with your own authentication logic
    $_SESSION['user_id'] = 1; // Replace 1 with the actual user ID

    // After successful login, fetch and return the user's wishlist items
    if (isset($_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];

    // Fetch the user's wishlist items from the database
    $stmt = $pdo->prepare("SELECT * FROM wishlist WHERE user_id = ?");
    $stmt->execute([$userId]);
    $wishlistItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Output the wishlist items as JSON for JavaScript to handle
    echo json_encode($wishlistItems);
}
}
?>
Posted
Comments
Andre Oosthuizen 24-Oct-23 3:57am    
You need to to stop asking ChatGPT for answers, copying that answer without understanding the code and it's flow and then paste it here for a solution. If you go back to when you started asking questions a year ago, your issues made sense and we were able to help you. Since then most of your recent code is ChatGPT code (easy to spot looking at the code and it's format with comments) which tells me that you are not doing the work yourself, this will start identifying you as a nefarious code vampire.

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