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
0
//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(`${item.product_name} `);
});
}
},
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
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);
?>
Chris LovePosted Oct 15, 2023, 7:00 AM
Sure! Let's clean up the code step by step.
Step 1: Use the Fetch API The Fetch API provides a more modern way to make web requests and is built into modern browsers. It returns Promises, which can be used with async/await to write more readable asynchronous code.
Reasons to use the Fetch API over jQuery's AJAX:
No Dependency: Fetch is built into modern browsers, so you don't need an external library. Promises: Fetch is promise-based, which is more modern than jQuery's callback-based AJAX. Readable: With async/await, Fetch becomes even more readable than jQuery's AJAX. Step 2: Use Async/Await Async/await is a way to handle Promises that makes asynchronous code look and behave a bit more like synchronous code. This makes the code more readable and easier to understand.
Step 3: Clean up the PHP We will organize the PHP code to make it cleaner.
Let's start with the JavaScript:
For the PHP:
Notes: I've replaced jQuery AJAX with Fetch API and used async/await for asynchronous operations. I've organized the PHP code to make it cleaner and added a try-catch block to handle potential PDO exceptions. Make sure to replace placeholders like database connection details with actual values. The code assumes that add-to-wishlist is a class assigned to multiple elements. If it's an ID for a single element, replace document.querySelectorAll with document.getElementById and adjust the logic accordingly.