I have the following code which I am using for a simple LIKE system on my site. The problem I am having is that if a user clicks like, the css style changes as it should, but if the user clicks it again it should then unlike. This is not happening, if the like is clicked twice it likes it twice rather than like/unlike.
The JS:
// ADD THE LIKE
$(function() {
$(".like").click(function() {
var item_id = $(this).attr("id");
$('a#' + item_id).removeClass("like");
$.ajax({
type: "POST",
url: "statAdd.php",
data: "item_id=" + item_id + "&uname=" + "<?php echo $memName; ?>" + "&uID=" + "<?php echo $memID; ?>" + "&statType=" + "like",
cache: false,
success: function(data) {
$('a#' + item_id).addClass("liked");
$('a#' + item_id).html(data);
}
});
return false;
});
});
// REMOVE THE LIKE
$(function() {
$(".liked").click(function() {
var item_id = $(this).attr("id");
$('a#' + item_id).removeClass("liked");
$.ajax({
type: "POST",
url: "statAdd.php",
data: "item_id=" + item_id + "&uname=" + "<?php echo $memName; ?>" + "&uID=" + "<?php echo $memID; ?>" + "&statType=" + "liked",
cache: false,
success: function(data) {
$('a#' + item_id).addClass("like");
$('a#' + item_id).html(data);
}
});
return false;
});
});
The AJAX server code returns the following data on success:
// ADD LIKE
echo '<i class="fa fa-heart"></i> <span>'.$number.' Likes including you</span>';
// REMOVE LIKE
echo '<i class="fa fa-heart"></i> <span>'.$number.' Likes</span>';
This is the HTML:
<?php
// Check if the user has liked the post previously.
if(mysqli_num_rows($qryLikes) == 0){
echo '<a href="javascript:void();" title="LIKE THIS" class="like" id="'.$statRow['statID'].'"><i class="fa fa-heart"></i> <span>'.$likes.' Likes</span></a>';
} else {
echo '<a href="javascript:void();" title="UNLIKE THIS" class="liked" id="'.$statRow['statID'].'"><i class="fa fa-heart"></i> <span>'.$likes.' Likes including you</span></a>';
}
?>
Is there anyone out there that can point me to my error?
Kind regards