Gcobani Mkontwana

Gcobani Mkontwana

  • 557
  • 1.9k
  • 407.5k

How to fix error product does not exist?

Oct 12 2023 1:08 AM

Hi Team

I am debugging an error log and notice when inserting a data from both client side(javascript and html). Its expecting some additional fields from the database. My connection is fine, but if it says " must include all my table defitions from wishlist or products?

{
  "success": false,
  "message": "Required data missing."
}

// html code

< 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">Colorful Stylish 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  class="btn btn-sm text-dark p-0"><i class="fas fa-eye text-primary mr-1"></i>View Detail</a>
            <a  class="btn btn-sm text-dark p-0 add-to-wishlist" data-id="12"
             data-product-name="Colorful Stylish Shirt"
             data-product-image="img/wishlist-img/SecondWishlist.jpg">
            <i class="fas fa-heart text-danger mr-1"></i>Add To Wishlist</a>
        </div>
    </div>
</div>

/***
@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");
        //const productCode = $(this).data("product_code");

        // 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({
            l: '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
ob_start(); // Start output buffering to prevent header issues

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

session_start();

// Check if the user is logged in or not
if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
} else {
    $user_id = 0;
}

// Check if the required POST values exist
if (isset($_POST['product_name'], $_POST['product_image'])) {
    $product_name = $_POST['product_name'];
    $product_image = $_POST['product_image'];
    //$product_code = $_POST['product_code'];
    // $product_code = isset($_POST['product_code']) ? $_POST['product_code'] : '';
    
    try {
        // Establish a database connection
        $pdo = new PDO("mysql:host=localhost;dbname=db;charset=utf8", "username", "password");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // 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 ";
        $productStmt = $pdo->prepare($productQuery);
        $productStmt->bindParam(":product_name", $product_name, PDO::PARAM_STR);
        $productStmt->bindParam(":product_image", $product_image, 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_id) VALUES (:user_id, :product_name, :product_image)";
            $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->execute();

            $response = array("success" => true, "message" => "Product added to your wishlist.");
        } else {
            $response = array("success" => false, "message" => "Product does not exist.");
        }
    } catch (PDOException $e) {
        // Handle database connection or query errors
        $response = array("success" => false, "message" => "Database error: " . $e->getMessage());
    }
} else {
    // If required POST values are missing
    $response = array("success" => false, "message" => "Required data missing."); // issue is here
}

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

ob_end_flush(); // End output buffering
?>

 


Answers (1)