Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Like unlike using AJAX, jQuery and PHP

In this tutorial, we are going to learn how to add like and unlike button within the post using jQuery, Ajax, and PHP.

What we are gone build in this tutorial is – We 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 post. Whenever user clicked on a button the value of label gets changed.

Demo  Download

Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. AJAX
  5. jQuery
  6. Conclusion

1. Table structure

We are using two tables in this tutorial 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

In this tutorial, we are using a tutorial database.

Completed Code


3. HTML

In HTML we are creating our structure and displaying posts which contain title, content, and like, unlike button. We are doing PHP work over here for getting all posts from the table and counting total like and unlike on that post. Within the loop, we have set up our post structure. If a user has performed some action on the post then we change the button color.

We have added classes on Like and Unlike buttons, like buttons have class="like" and unlike have class="unlike".

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

Completed Code

Like & Unlike using jQuery,AJAX, and PHP
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']; ?>

" /> (" /> ()

4. AJAX

Our AJAX file name is likeunlike.php. We have fixed userid value to 5 here which you may change, you can use $_SESSION variable for getting login user id. From AJAX request in jQuery, we are sending postid and type.

Here, if type value is

0 – means user have clicked, unlike button.

1 – means user have clicked like the button.

Explanation –

We are first storing $_POST values in variables ($postid and $type) then checking that user have performed some action on it (like or unlike the post), for these we checking it on the like_unlike table. If entry found then we update otherwise insert new entry within the table.

After updating table we are counting total like and unlike on that post and creating an associative array, we initialize it with the total like and unlike values. Then we encode it in JSON format using json_encode for returning data.

Completed Code

$totalLikes,"unlikes"=>$totalUnlikes);

echo json_encode($return_arr);

5. jQuery

We have added classes (like and unlike) to buttons while creating post structure.  We are using this classes for completing our operation when this class element get clicked.

Explanation –

We first storing current element id and splitting it for getting postid then finding that user clicked like or unlike button.

If user clicked button –

like – set type variable value to 1

unlike – set type variable value to 0

In AJAX request, we are sending postid and type as data. When AJAX request successfully then we are using return data for setting total likes and unlikes.

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

We have learned in this that how you can implement like and unlike functionality within your project. We have used AJAX for updating our table data when like and unlike button get clicked. We have used fixed userid in the tutorial example which you can change in your project. You can replace it with your user id value or you can use $_SESSION variable if you have created a variable for storing user id.

Related Post

Loops in PHP
$_GET, $_POST and $_REQUEST in PHP
jQuery Autocomplete search
Embedding PHP in HTML

The post Like unlike using AJAX, jQuery and PHP appeared first on Makitweb.



This post first appeared on Makitweb, please read the originial post: here

Share the post

Like unlike using AJAX, jQuery and PHP

×

Subscribe to Makitweb

Get updates delivered right to your inbox!

Thank you for your subscription

×