Like unlike using AJAX, jQuery and PHP

Like unlike functionality used in many websites to know the user response on 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 this posts they have like and unlike button. It also has a label which shows how many like and unlike get by a post. Whenever user clicked on a button the value of label gets changed.

Like unlike using AJAX, jQuery and PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. jQuery
  6. 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 establishing the database connection.

Completed Code

<?php

$host = "localhost";    /* Host name */
$user = "root";         /* User */
$password = "";         /* Password */
$dbname = "tutorial";   /* Database name */

$con = mysql_connect($host, $user, $password) or die("Unable to connect");

// selecting database
$db = mysql_select_db($dbname, $con) or die("Database not found");

 

3. HTML

In HTML creating our structure and displaying posts which contain title, content, and like, unlike button.

Using PHP to get all posts from the table and counting total like and unlike on that post.

If a user has performed some action on the post then we change the button color using jQuery.

Note – here I am using postid for creating like and unlike button ids. This one is we use in jQuery for identifying what post button is clicked.

Completed Code

<div class="content">

  <?php
   $userid = 5;
   $query = "SELECT * FROM posts";
   $result = mysql_query($query);
   while($row = mysql_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 = mysql_query($status_query);
    $status_row = mysql_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 = mysql_query($like_query);
    $like_row = mysql_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 = mysql_query($unlike_query);
    $unlike_row = mysql_fetch_array($unlike_result);
    $total_unlikes = $unlike_row['cntUnlikes'];

   ?>
    <div class="post">
     <h1><?php echo $title; ?></h1>
     <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 a likeunlike.php file.

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.

From AJAX request in jQuery, sending postid and type.

Here, if type value is –

0 – means user have clicked, unlike button.

1 – means user have clicked like the button.

How it’s works –

First storing $_POST values in variables ($postid and $type) then check the user has performed which action on it (like or unlike the post).

After finding the action status check the entry on the like_unlike table if the entry is found then update the status otherwise insert the new record.

Counting the total number of likes and unlikes on that post and returning 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 = mysql_query($query);
$fetchdata = mysql_fetch_array($result);
$count = $fetchdata['cntpost'];


if($count == 0){
    $insertquery = "INSERT INTO like_unlike(userid,postid,type) values(".$userid.",".$postid.",".$type.")";
    mysql_query($insertquery);
}else {
    $updatequery = "UPDATE like_unlike SET type=" . $type . " where userid=" . $userid . " and postid=" . $postid;
    mysql_query($updatequery);
}


// count numbers of like and unlike in post
$query = "SELECT COUNT(*) AS cntLike FROM like_unlike WHERE type=1 and postid=".$postid;
$result = mysql_query($query);
$fetchlikes = mysql_fetch_array($result);
$totalLikes = $fetchlikes['cntLike'];

$query = "SELECT COUNT(*) AS cntUnlike FROM like_unlike WHERE type=0 and postid=".$postid;
$result = mysql_query($query);
$fetchunlikes = mysql_fetch_array($result);
$totalUnlikes = $fetchunlikes['cntUnlike'];

// initalizing array
$return_arr = array("likes"=>$totalLikes,"unlikes"=>$totalUnlikes);

echo json_encode($return_arr);

 

5. jQuery

Sending AJAX request when .like and .unlike class element gets clicked.

Passing postid and action status on AJAX as data. Using response which returns on AJAX success to update the layout.

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

On the demonstration, I used like unlike on the Post list you can either use this on any other cases for example – For getting the response on your web design from your registered users or using it in the comment section, etc.

Related Post

Spread the love

12 Comments

  1. hung nguyen said:

    thanks you very much

    March 16, 2017
    Reply
  2. Sanjay Kumar said:

    Hello,

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

    Thank You

    May 4, 2017
    Reply
    • Yogesh Singh said:

      They are count(*) alias variable names for easier access and not relate to table column name.

      May 4, 2017
      Reply
  3. Ivanet said:

    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

    June 6, 2017
    Reply
    • Yogesh Singh said:

      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.

      June 7, 2017
      Reply
      • Ivanet said:

        YOU ARE THE MAN!
        I had a problem with the connection to the db.
        thanks.

        June 7, 2017
        Reply
          • ivan Pisoni said:

            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?

            July 11, 2017
          • Yogesh Singh said:

            I think it may be a database connection issue.

            What error message you are getting with mysql_query($query) or die(mysql_error());

            July 12, 2017
  4. ivan Pisoni said:

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

    July 17, 2017
    Reply
  5. boom said:

    I was trying to implement this into code igniter but couldn’t wrap my head around it can anyone help out. thanks

    July 24, 2017
    Reply
    • Yogesh Singh said:

      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.

      July 25, 2017
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *