John Davidson

javascript - How to make like button stay as liked state when refresh the page

0 comments
Message:


I'm working on a Like button. It's working just fine unless user refresh the page. When page is not refreshed the like button itself change the style and add 1 to the like count if user click on it. But when the page is refreshed the like button remain the like count and the previous style then add 1 to the like count and change to the new style if user click on it. That's the problem.


The like button looks like this:



Here is the Javascript code:


function addLikes(id,action) {
$.ajax({
url: "like.php",
data:'post_id='+id+'&action='+action,
type: "POST",
success: function(data){
var likes = parseInt($('#likes-'+id).val());
switch(action) {
case "like":
$('#like_area'+id).html('<i id="like'+id+'" class="fas fa-thumbs-up react"></i> Thích');
$('#like_area'+id).attr("onclick", "addLikes("+id+",'unlike')");
likes = likes+1;
$('#like_area'+id).addClass("liked");
break;
case "unlike":
$('#like_area'+id).html('<i id="like'+id+'" class="far fa-thumbs-up react"></i> Thích');
$('#like_area'+id).attr("onclick", "addLikes("+id+",'like')");
$('#like_area'+id).removeClass("liked");
likes = likes-1;
break;
}

$('#likes-'+id).val(likes);
if(likes>0) {
$('#people_liked'+id).html(kFormatter(likes));
$('#user_liked'+id).attr("style", "display:block;");
} else {
$('#user_liked'+id).attr("style", "display:none;");
}
}
});
}

Here is the PHP code in like.php:


<?php
session_start();
require $_SERVER['DOCUMENT_ROOT'] . '/require/serverconnect.php';

$username = $_SESSION['username'];
$post_id = $_POST['post_id'];
$action = $_POST['action'];

if(!empty($post_id)) {
switch ($action) {
case 'like':
$query = "INSERT IGNORE INTO tintuc_post_likes (username_of_like, liked_post_id) VALUES ('$username','$post_id')";
$result = mysqli_query($con, $query);
break;

case 'unlike':
$query = "DELETE FROM tintuc_post_likes WHERE username_of_like = '$username' AND liked_post_id = '$post_id'";
$result = mysqli_query($con, $query);
break;
}
}
?>

PHP Select code in index.php:


<?php
$sql = "SELECT tintuc_posts.id, tintuc_posts.author, tintuc_posts.content, tintuc_posts.timeofpost, tintuc_posts.has_comment, tintuc_posts.avatar, tintuc_posts.has_image, tintuc_posts.image, tintuc_posts.username, tintuc_posts.c4id, COUNT(tintuc_post_likes.like_id) as likes, GROUP_CONCAT(accounts.name separator '|') as liked_by
FROM tintuc_posts
LEFT JOIN tintuc_post_likes
ON tintuc_posts.id = tintuc_post_likes.liked_post_id
LEFT JOIN accounts
ON tintuc_post_likes.username_of_like = accounts.username
GROUP BY tintuc_posts.id
ORDER BY tintuc_posts.id DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
?>

Here is the tables:



My Answer:
To make the like button stay in the liked state when the page is refreshed, you can store the liked status in the browser's local storage. Here's how you can modify your JavaScript code to achieve this:

javascript
function addLikes(id, action) {
var likedPosts = JSON.parse(localStorage.getItem('likedPosts')) || {};

$.ajax({
url: "like.php",
data: 'post_id=' + id + '&action=' + action,
type: "POST",
success: function(data) {
var likes = parseInt($('#likes-' + id).val());

switch (action) {
case "like":
$('#like_area' + id).html(' Thích');
$('#like_area' + id).attr("onclick", "addLikes(" + id + ",'unlike')");
likes = likes + 1;
$('#like_area' + id).addClass("liked");
likedPosts[id] = true;
break;
case "unlike":
$('#like_area' + id).html(' Thích');
$('#like_area' + id).attr("onclick", "addLikes(" + id + ",'like')");
$('#like_area' + id).removeClass("liked");
likes = likes - 1;
delete likedPosts[id];
break;
}

localStorage.setItem('likedPosts', JSON.stringify(likedPosts));

$('#likes-' + id).val(likes);
if (likes > 0) {
$('#people_liked' + id).html(kFormatter(likes));
$('#user_liked' + id).attr("style", "display:block;");
} else {
$('#user_liked' + id).attr("style", "display:none;");
}
}
});
}

$(document).ready(function() {
var likedPosts = JSON.parse(localStorage.getItem('likedPosts')) || {};

for (var postId in likedPosts) {
if (likedPosts.hasOwnProperty(postId)) {
$('#like_area' + postId).addClass("liked");
}
}
});


In this code, we are storing the liked status of each post in the `likedPosts` object in the browser's local storage. When the page is refreshed, we retrieve this object from local storage and apply the liked class to the like button if the post is in the `likedPosts` object.

Make sure to include this code in your HTML file after including jQuery and before the like button elements.

Rate this post

3 of 5 based on 3333 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us