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, we are going to learn how to add like and unlike button within the post using jQuery, AJAX, and PHP.

In the tutorial, 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. AJAX
  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

I am using a tutorial database.

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

Our AJAX file name is likeunlike.php. 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.

Spread the love

Related Post

3 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

Leave a Reply

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