Like unlike using AJAX, jQuery and PHP

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.

Like unlike using AJAX, jQuery and PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. jQuery
  6. Demo
  7. Conclusion

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;"; } ?>" />&nbsp;(<span id="likes_<?php echo $postid; ?>"><?php echo $total_likes; ?></span>)&nbsp;

      <input type="button" value="Unlike" id="unlike_<?php echo $postid; ?>" class="unlike" style="<?php if($type == 0){ echo "color: #ffa449;"; } ?>" />&nbsp;(<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

View 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.

56 thoughts on “Like unlike using AJAX, jQuery and PHP”

  1. Hello,

    cntStatus, cntLike, cntUnlike, this columns is not defined in table which you written in the top,
    please tell me about this ?

    Thank You

    Reply
  2. 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

    Reply
  3. Actually i don’t get any error.. just the one I mentioned in the previous comment.
    I was hoping for something more ;-(

    Reply
  4. 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?

    Reply
  5. 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!

    Reply
  6. 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!

    Reply
  7. 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!

    Reply
  8. 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. 🙂

    Reply
  9. 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

    Reply
  10. 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:)

    Reply
  11. 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″}

    Reply

Leave a Comment