Guest User

Guest User

  • Tech Writer
  • 2.1k
  • 482.6k

How to add wishlist using jquery and server side?

Oct 11 2023 11:51 PM

Hi Team

I need some help, have html code for adding wishlist. Basically user supposed when adding wishlist it adds or increase an item to it. Then prompts user to login, then can be able to view those as list in the table with current user session. The issue is when i debug, notice client side is complaining user is not logged in and server side is doing the same. Let me share my logic below.

//wishlist badge to add items     

<a  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>

//javascript

$(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() {
        
        // Replace the following code with your actual request:
        $.ajax({
            ..l: 'get-wishlist-product.php', 
            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);
            }
        });
    });
});

// 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=testdb;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);
?>

 


Answers (1)