I'm trying to make a wishlist with the heart icon. If user clicks on the icon, it will save the product into the database and display the icon in red color. If users click on the red color icon again, it will turn grey and the item is deleted from the database.
My controller.php is working fine as I am able to add and delete previously. But the toggling part of the heart icon is not working. As of now, nothing happens when I clicked on the heart button.
itemInfo.php
<?php if($countid['cnt'] == '1'): ?>
<a class='addToWishlist' href='javascript:;' data-data=".$itemPost['item_id']."><i class='fa fa-heart wishstate'></i></a>
<?php else:?>
<a class='addToWishlist' href='javascript:;' data-data=".$itemPost['item_id']."><i class='fa fa-heart wishstate active'></i></a>
<?php endif;?>
controller.php
<?php
require_once ('config/dbfunctions.php');
$table = 'wishlist';
if(isset($_POST['item_id'])) {
$_POST['user_id'] = $_SESSION['user_id'];
$user_id = $_POST['user_id'];
$_POST['item_id'] = $_GET['item_id'];
$item_id = $_POST['item_id'];
$sql= "SELECT count(item_id) count FROM wishlist WHERE user_id = ? AND item_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $user_id,$item_id );
$stmt->execute();
$countid = $stmt->get_result()->fetch_assoc();
if($countid['count'] == 1){
// If item is already added to wishlist, remove it from db
$count = deleteWishlist($table, $user_id,$item_id );
} else {
// If item is not in wishlist, add to db
$wishlist_id= create($table, $_POST);
}
}
Ajax
<script type="text/javascript">
$(document).ready(function(){
$(".addToWishlist").on('click', function(e) {
var link_data = $(this).data('data');
$.ajax({
type: "POST",
url: 'itemInfo.php',
data: ({item_id: link_data}),
success: function(data) {
$('a[data-data="' + link_data + '"] > i.heartStatus').toggleClass("active");
}
});
});
});
</script>