Wishlist part 2

 To add a product to a user's wishlist when they click a "Wishlist" button and store it in a database, you can use JavaScript to make an AJAX request to a PHP script that handles the database interaction. Here's a basic example:


**HTML for the Wishlist Button:**


```html

<!-- Add this button to your product page -->

<button id="wishlistButton" onclick="addToWishlist(123)">Add to Wishlist</button>

```


In this example, `123` is the product ID. Replace it with the actual product ID you want to add to the user's wishlist.


**JavaScript for Adding to Wishlist:**


```html

<script>

function addToWishlist(product_id) {

    // Check if the user is logged in (you might use a PHP session or other method)

    var userLoggedIn = true; // Replace with your login check


    if (userLoggedIn) {

        // User is logged in, proceed to add the product to the wishlist

        $.ajax({

            type: "POST",

            url: "add_to_wishlist.php", // Replace with the actual URL of your PHP script

            data: { product_id: product_id },

            success: function(response) {

                if (response === "success") {

                    alert("Product added to your wishlist.");

                } else {

                    alert("Error adding the product to your wishlist.");

                }

            }

        });

    } else {

        // User is not logged in, handle this case (e.g., show a login popup)

    }

}

</script>

```


In the above code, we use jQuery for making the AJAX request. Make sure you include jQuery in your HTML file for this to work.


**PHP for Adding to Wishlist (`add_to_wishlist.php`):**


```php

<?php

// Check if the user is logged in (you might use a session or other method)

$userLoggedIn = true; // Replace with your login check


if ($userLoggedIn) {

    // Get the product_id from the AJAX request

    $product_id = $_POST['product_id'];


    // Add the product to the wishlist in the database

    // Implement this part using an SQL INSERT statement


    // Check if the product was successfully added to the wishlist

    if (/* Insert success condition here */) {

        echo "success";

    } else {

        echo "error";

    }

} else {

    echo "login_required"; // You can handle this case on the client-side

}

?>

```


In the `add_to_wishlist.php` script, replace the placeholder comments with your actual database interaction code, including the SQL `INSERT` statement to add the product to the user's wishlist. The script returns either "success" or "error" to the JavaScript function, and you can show appropriate messages to the user.

Previous
Next Post »