Skip to content
var rateStars = document.querySelectorAll('.likebtn');
rateStars.forEach(function (v, i) {
v.addEventListener("click", function (t) {
// Prevent default link behavior
t.preventDefault();
// Get the post ID
const postid = jQuery(v).find('a').attr('id');
console.log("Post ID:", postid);
// Immediately update the UI
let oldLike = parseInt(jQuery(v).find('a .elementor-button-text').text()) || 0; // Handle 0 or no post_rate
let newLike = oldLike + 1;
// Update like count and button styles
jQuery(v).find('a .elementor-button-text').text(newLike);
jQuery(v).addClass('liked'); // Add 'liked' class to trigger the CSS
jQuery(v).css('pointer-events', 'none'); // Prevent multiple clicks
// Send the AJAX request
jQuery.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 () {
alert('Error occurred while submitting your like!');
// Rollback the UI changes on failure
jQuery(v).find('a .elementor-button-text').text(oldLike); // Revert like count
jQuery(v).removeClass('liked'); // Remove 'liked' class
jQuery(v).css('pointer-events', ''); // Re-enable button
}
});
});
});