Skip to content
jQuery(document).ready(function ($) {
// Handle like button click
$(".likebtn").on("click", function () {
const likeButton = $(this);
const likeCountSpan = likeButton.find(".like-count");
const postId = likeButton.data("post-id");
// Prevent multiple clicks
if (likeButton.hasClass("liked")) {
return;
}
// Optimistically update the like count
const currentCount = parseInt(likeCountSpan.text());
likeCountSpan.text(currentCount + 1);
// Add 'liked' class to change heart fill
likeButton.addClass("liked");
// Send the AJAX request
$.ajax({
url: "https://ketabpedia.com/wp-json/codecraft/v1/like",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ postId: postId }),
success: function () {
console.log("Like successfully posted");
},
error: function () {
// Revert changes if AJAX fails
console.error("Failed to post like");
likeButton.removeClass("liked");
likeCountSpan.text(currentCount); // Revert the count
},
});
});
});