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:
<pre><!--
<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>
document.addEventListener('DOMContentLoaded', async function() {
let wishlistCount = 0;
let wishlistItems = [];
function updateWishlistBadge() {
document.getElementById("wishlist-badge").textContent = wishlistCount;
}
function openLoginModal() {
$('#wishlistLoginModal').modal("show");
}
function displayWishlist(wishlistItems) {
console.log('Received wishlist items:', wishlistItems);
const wishlistTable = document.getElementById('wishlistTable').getElementsByTagName('tbody')[0];
wishlistTable.innerHTML = '';
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;
cell2.innerHTML = `<img src="${item.product_image}" alt="${item.product_name}" class="img-thumbnail">`;
cell3.textContent = 'R' + item.product_price.toFixed(2);
cell4.textContent = item.quantity;
});
}
wishlistItems = JSON.parse(sessionStorage.getItem('wishlistItems')) || [];
wishlistCount = parseInt(sessionStorage.getItem('wishlistCount')) || 0;
updateWishlistBadge();
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);
wishlistCount++;
updateWishlistBadge();
wishlistItems.push({ productId, productName, productImage });
sessionStorage.setItem('wishlistItems', JSON.stringify(wishlistItems));
sessionStorage.setItem('wishlistCount', wishlistCount);
});
});
document.getElementById("wishlist-badge").addEventListener('click', function() {
console.log("Wishlist badge clicked");
if (wishlistCount > 0) {
openLoginModal();
}
});
async function onLogin() {
if (wishlistCount > 0) {
fetchWishlistItems().then((wishlistItems) => {
console.log('Received wishlist items:', wishlistItems);
displayWishlist(wishlistItems);
});
}
}
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
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'];
$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'])) {
$userId = $_SESSION['user_id'];
$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) {
echo json_encode(['success' => false, 'message' => 'Item is already in the wishlist.']);
} else {
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$productId]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);
if ($product) {
$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 {
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);
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'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['user_id'] = 1;
if (isset($_SESSION['user_id'])) {
$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM wishlist WHERE user_id = ?");
$stmt->execute([$userId]);
$wishlistItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($wishlistItems);
}
}
?>