-1

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>
NatanataC
  • 1
  • 1
  • 3
  • That first code block is invalid, HTML inside PHP – brombeer May 18 '22 at 04:37
  • @brombeer but don't know why it didn't show any errors in my editor – NatanataC May 18 '22 at 04:44
  • Me neither - I don't know which editor you use. Now that you've changed it, it still is invalid: PHP variables without PHP inside HTML. Don't edit code around here but paste your original code. Turn on error reporting ([How do I get PHP errors to display?](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display?rq=1)), debug your AJAX calls using your browsers DevTools/Network tab to see if any errors occur. Check your Javascript, make sure you use the correct selector, there is no element `i.heartStatus`! – brombeer May 18 '22 at 04:50

0 Answers0