Like unlike functionality used in many websites to know the user response to their content or article.
In this tutorial, I will add like and unlike buttons within the content and handle with jQuery and PHP.
In the demonstration, I will show the list of posts within these posts they have like unlike button.
It also has a label that shows how many totals like and unlike gets a post. Whenever the user clicked on a button the value of the label gets changed.
Contents
1. Table structure
I am using two tables in the example.
posts table
CREATE TABLE `posts` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `title` varchar(100) NOT NULL, `content` text NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
like_unlike table
CREATE TABLE `like_unlike` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `userid` int(11) NOT NULL, `postid` int(11) NOT NULL, `type` int(2) NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a config.php
file for the database connection.
Completed Code
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
3. HTML
Creating layout where display posts that contain title, content, and like, unlike button.
Fetch records from the posts
table and count total like and unlike on the posts.
Also, select the user attempt on the post from like_unlike
table and change button color accordingly.
Note – I am using
postid
for creating like and unlike button ids. This one is use in jQuery for identifying what post button is clicked.
Completed Code
<div class="content"> <?php $userid = 5; $query = "SELECT * FROM posts"; $result = mysqli_query($con,$query); while($row = mysqli_fetch_array($result)){ $postid = $row['id']; $title = $row['title']; $content = $row['content']; $type = -1; // Checking user status $status_query = "SELECT count(*) as cntStatus,type FROM like_unlike WHERE userid=".$userid." and postid=".$postid; $status_result = mysqli_query($con,$status_query); $status_row = mysqli_fetch_array($status_result); $count_status = $status_row['cntStatus']; if($count_status > 0){ $type = $status_row['type']; } // Count post total likes and unlikes $like_query = "SELECT COUNT(*) AS cntLikes FROM like_unlike WHERE type=1 and postid=".$postid; $like_result = mysqli_query($con,$like_query); $like_row = mysqli_fetch_array($like_result); $total_likes = $like_row['cntLikes']; $unlike_query = "SELECT COUNT(*) AS cntUnlikes FROM like_unlike WHERE type=0 and postid=".$postid; $unlike_result = mysqli_query($con,$unlike_query); $unlike_row = mysqli_fetch_array($unlike_result); $total_unlikes = $unlike_row['cntUnlikes']; ?> <div class="post"> <h2><?php echo $title; ?></h2> <div class="post-text"> <?php echo $content; ?> </div> <div class="post-action"> <input type="button" value="Like" id="like_<?php echo $postid; ?>" class="like" style="<?php if($type == 1){ echo "color: #ffa449;"; } ?>" /> (<span id="likes_<?php echo $postid; ?>"><?php echo $total_likes; ?></span>) <input type="button" value="Unlike" id="unlike_<?php echo $postid; ?>" class="unlike" style="<?php if($type == 0){ echo "color: #ffa449;"; } ?>" /> (<span id="unlikes_<?php echo $postid; ?>"><?php echo $total_unlikes; ?></span>) </div> </div> <?php } ?> </div>
4. PHP
Create likeunlike.php
file for handling AJAX requests.
I fix the userid
value to 5
which you can change on your project or you can use $_SESSION
variable for getting login user id.
Here, if $type
value is –
0 – means user have clicked, unlike button.
1 – means user have clicked a like button.
Check if a user has any record in like_unlike
table on the post. If not then insert a new record otherwise update the record.
Count total like unlike on the $postid
and initialize $return_arr
with the counts.
Return an Array in JSON format.
Completed Code
<?php include "config.php"; $userid = 5; $postid = $_POST['postid']; $type = $_POST['type']; // Check entry within table $query = "SELECT COUNT(*) AS cntpost FROM like_unlike WHERE postid=".$postid." and userid=".$userid; $result = mysqli_query($con,$query); $fetchdata = mysqli_fetch_array($result); $count = $fetchdata['cntpost']; if($count == 0){ $insertquery = "INSERT INTO like_unlike(userid,postid,type) values(".$userid.",".$postid.",".$type.")"; mysqli_query($con,$insertquery); }else { $updatequery = "UPDATE like_unlike SET type=" . $type . " where userid=" . $userid . " and postid=" . $postid; mysqli_query($con,$updatequery); } // count numbers of like and unlike in post $query = "SELECT COUNT(*) AS cntLike FROM like_unlike WHERE type=1 and postid=".$postid; $result = mysqli_query($con,$query); $fetchlikes = mysqli_fetch_array($result); $totalLikes = $fetchlikes['cntLike']; $query = "SELECT COUNT(*) AS cntUnlike FROM like_unlike WHERE type=0 and postid=".$postid; $result = mysqli_query($con,$query); $fetchunlikes = mysqli_fetch_array($result); $totalUnlikes = $fetchunlikes['cntUnlike']; // initalizing array $return_arr = array("likes"=>$totalLikes,"unlikes"=>$totalUnlikes); echo json_encode($return_arr);
5. jQuery
On like unlike button click split the id to get the postid
.
Send an AJAX request where pass the postid
and type
.
On successful callback update total counts on the elements with data['likes']
and data['unlikes']
.
Change the color of the button based on the click.
Complete Code
$(document).ready(function(){ // like and unlike click $(".like, .unlike").click(function(){ var id = this.id; // Getting Button id var split_id = id.split("_"); var text = split_id[0]; var postid = split_id[1]; // postid // Finding click type var type = 0; if(text == "like"){ type = 1; }else{ type = 0; } // AJAX Request $.ajax({ url: 'likeunlike.php', type: 'post', data: {postid:postid,type:type}, dataType: 'json', success: function(data){ var likes = data['likes']; var unlikes = data['unlikes']; $("#likes_"+postid).text(likes); // setting likes $("#unlikes_"+postid).text(unlikes); // setting unlikes if(type == 1){ $("#like_"+postid).css("color","#ffa449"); $("#unlike_"+postid).css("color","lightseagreen"); } if(type == 0){ $("#unlike_"+postid).css("color","#ffa449"); $("#like_"+postid).css("color","lightseagreen"); } } }); }); });
6. Demo
7. Conclusion
On the example, I used like unlike on the Post list you can either use this on any other cases for example – To get the response on your web design from your registered users or using it in the comment section, etc.
If you found this tutorial helpful then don't forget to share.
thanks you very much
Hello,
cntStatus, cntLike, cntUnlike, this columns is not defined in table which you written in the top,
please tell me about this ?
Thank You
They are count(*) alias variable names for easier access and not relate to table column name.
hi there, great work, just what I was looking for but even if it works like a charme locally, remotely it get stuck when hitting the “like” button.
An alert appears giving:
error : {“readyState”:4,”responseText”:”\nWarning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /web/htdocs/www.mysite.it/home/likeunlike.php on line 12… 28 and 33.
Basically on $fetchdata = mysql_fetch_array($result);, $fetchlikes = mysql_fetch_array($result); and $fetchunlikes = mysql_fetch_array($result);.
The page where the like button is http://www.mysite.it/it/mypage.html and the script.js and the likeunlike.php are on the root of the site that I call it via :
/script.js
and
$.ajax({
url: ‘/likeunlike.php’, …
Any idea on what am I doing wrong?
I’ve also tried url: ‘../likeunlike.php’, and with the full domain but no success on my server.
Can you help?
Thanks
Replace
$result = mysql_query($query);
with$result = mysql_query($query) or die(mysql_error());
which is before$fetchlikes = mysql_fetch_array($result);
to know what is causing problem.YOU ARE THE MAN!
I had a problem with the connection to the db.
thanks.
Thanks
Sorry to bother again but somehow, even thou for a few days everything was working, I’m facing the same problem: when I click on the Like link an alert appears saying
“error : {“readyState”:4,”responseText”:”\nWarning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /web/htdocs/www.mysite.it/home/it/likeunlike.php on line 12\n\nWarning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /web/htdocs/www.mysite.it/home/it/likeunlike.php on line 28\n\nWarning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /web/htdocs/www.mysite.it/home/it/likeunlike.php on line 33\n{\”likes\”:null,\”unlikes\”:null}”,”status”:200,”statusText”:”OK”}”
…I guess is again an error connecting to the DB but even I have “$result = mysql_query($query) or die(mysql_error());” I don’t get a clue of what is wrong.
I’m really hitting my head on the wall with this.
I’m afraid I’ve overwrtitten something but it’s like 3 hours I’m checkin everything all all seems to be ok… for sure I am missing something.
Given that:
line 12 is just after “$db = mysql_select_db($dbname, $con) or die(“Database not found”);”
line 28 is just after “mysql_query($insertquery);”
line 33 is just after the same above
Can you help?
I think it may be a database connection issue.
What error message you are getting with mysql_query($query) or die(mysql_error());
Actually i don’t get any error.. just the one I mentioned in the previous comment.
I was hoping for something more ;-(
I was trying to implement this into code igniter but couldn’t wrap my head around it can anyone help out. thanks
I don’t have a tutorial on Codeigniter.
I will try to publish a tutorial on this soon. Meanwhile, subscribe our newsletter to get notified.
This is great! thank you very much
Thanks for reading!
Totaly output is wrong if anyone unlike first then why like is decreaseing.
Hi Nitish,
The output is not wrong. It is based on a user if a user is already liked the post and try to unlike then his like count removed and unlike count on the post increase.
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\practice\like-unlike-using-ajax-jquery-php\index.php on line 22
why showing this error?
There will be an error in your SQL query that’s why you are viewing this error. To debug this add die(mysqli_error($con)) with mysqli_query().
E.g. mysqli_query($con,$query) or die(mysqli_error($con));
Hi bro,
This tutorial working very smart and thanks for it buddy.
Now i am trying to implement Your this nice tutorial in my dynamic Php mysql Site which is am building but i got error like ankit said.
i am just changed few things with your tutorial, that is:
1. $userid=$_SERVER[‘REMOTE_ADDR’]; // getting user id by users IP
2 . $postid=intval($_GET[‘nid’]); // Dynamic Post Id from DB
I changed this changes in both index.php and likeunlike.php
But still getting error bro, can you help me Please, Waiting for your reply, Thanks.
Hi Boobalu,
Have you tried running your generated SQL query in phpMyAdmin? Is it working fine there?
Bro can’t understand your point because there is no error and no reaction when i clicks the like/dislike buttons then how can i point out which query is being wrong to run in phpmyadmin for correct it.
my concept is like/unlike for every single posts/articles in my site which displays in single page instead of like/dislike the group of posts in single page,Please help me bro, why there is no reaction, i just cant figure why its not running.
Hi bro,
Afrer spent lots of time, it finally working.
Now its not working while passing userid as ip address of user,that is if change userid= $_SERVER[‘REMOTE_ADDR’];
Its not working bro(it giving mysqli error bcz of the result is not successful).
Please Help me on how to use userid as ip adddress of users.
I am waiting for your reply bro.
To view the SQL query you need to echo the Query string then add die(); e.g. echo $query; die();. A query is then visible in Browser developer Tools->Network tab. You need to select the AJAX file from there.
Hi bro,
Finallay its work as per i needed, the problem was in mysql inser,t update, select queries that is userid=’$userid’ not userid=”. $userid. ” and datatype to store ip address is varchar, i worked lots of days in this to fix, finally i got success, Thanks a lot bro, its all bcz of you, Thank you so much, Stay blessed n long live bro 🙂
You’re welcome.
Hi, how would I do this using sqlite3 instead of mysql?
Hello, please tell me how to use the session in this script?
Hi Dominic,
Add session_start() at the top in the config.php file and in AJAX file assign $_SESSION[‘userid’] to $userid variable. Here, I am assuming you have $_SESSION[‘userid’] variable. You can change it if you any other SESSION variable.
Hi!
I have entered all my db info and created the tables in phpmyadmin and copied everything, but on my site it just displays an empty div:
What did i wrong?
Thanks a lot!
Hi Loro,
On your page check if data is fetching from MySQL database or not.
Hey Yogesh,
I don’t know why but now everything works, the buttons haven’t been displayed because my css styled them at the bottom of the page. Maybe I was too tired yesterday at night. 🙂
Thank you so much – great job, keep up the great work.
Best greetings!
But i noticed that the like function only works once for me, (in the demo it works with more than one like) even from another device with another connection…
Hi Yogesh
I could implemented your code to my project. My question is that, how can I undo the like or unlike? I can’t completely remove my like/unlike from a post, just stays there, but everything working well.
Thanks for this cool tutorial!
Hi Chris,
You need to update both JavaScript and PHP code. For undo you can either delete the link unlike entry record or create a new field to mark that no action is performed by the user in PHP script. In JavaScript code update AJAX successful callback function code based on the new return response.
Those things are makes sense, but I have no idea what should I change/add.
Hi Chris,
I emailed you the working code.
Hello Yogesh,
Please can you write a tutorial for undo the like/dislike if it has been submitted or explain what should I change to be able do that? Thanks in advance!
Hi Laure,
I emailed you the working code.
yeah its working nice
Glad you found this helpful.
Everything works as it should except the buttons and values only update if you refresh the page
Hi Matthew,
Is any error displaying in the browser console?
I have fixed that error but currently if I was to like a post then com back to the site after liking the post would still have my like but it does not display that I have liked the post but when I click the like button again it goes to what it should be
site: http://bulletin.tk/Pages/article.php?article=1
NOT WORKING
Hi Prashant,
What issue are you getting?
Hello! I tried to use the code for the author.php file from WordPress, but nothing appears. Is it possible to use like this? What modification to do to adjust for WordPress? Thanks. 🙂
Hi Yogesh,
this looks good, but, possible to PM you?
Can I use the contact form of this website to get in touch with you directly?
Thanks
Hi Norm,
Yes, you can or mail me at makitweb@gmail.com.
Hello Yogesh,
Very impressive work. Implemented dynamically to multi user successfully.everything is working fine.
if this can be improved further as undo the like/dislike buttons.it would be great.
Anyways Great job.
Thankyou:)
This has really helped me. Thanks for the pro tutorial mate.
However, I’m still stuck at something. It doesn’t update unless there’s page refresh.. :/
hello sir, Im new to ajax. so its extra confusing. I implemented same code, but seems like ajax request isnt working.
im getting following error:
Notice: Undefined index: postid in C:\xampp\htdocs\cms\post.php on line 69
Notice: Undefined index: type in C:\xampp\htdocs\cms\post.php on line 70
{“likes”:”0″,”unlikes”:”0″}
Hi fathima,
It may be because values are not posting with the request. Have you checked what data passing with AJAX request using the browser network tab?
yes. values are not posting with the requests. but unable to find the reason. and I also checked browser’s network tab. And there is no entry of ajax requests made within xhr tab.
Hi Fathima,
Can you share code at makitweb@gmail.com so I can check it?
sure sir. I’ll mail my code. I tried to catch error with ajax call. got followinng error.
SyntaxError: Unexpected token < in JSON at position 4
at JSON.parse ()
at m.parseJSON (jquery.js:4)
at Pc (jquery.js:4)
at x (jquery.js:4)
at XMLHttpRequest.b (jquery.js:4)
not sure if its problem related with jquery. I tried both cdn and local file.
hi , nice tutorial , but I want this with live notification , if you could tell me .