Sep
26

Facebook Style Like/Unlike button with Collapsed Comments Script using jQuery and PHP.

Another post in facebook style tutorials series at 99Points.info. You have seen facebook like/unlike button if you want to like a post you simple click on “Like” button. Also, you have seen collapsed comments there and when you click on show all comments button it shows all comments. I created this thing and I tried to create same style as it is on facebook. Please share this if you like and dont forget to subscribe by email.
Note: No spams and newsletters for subscribers. Thanks !

No Spams or Newsletters will be send to Subscribers.

Enter your email to subscribe :

Delivered by FeedBurner


Other Facebook Style Tutorials + Popular Tutorials on 99Points

Database Structure

I used 4 tables for this tutorial, one for saving posts, other for saving comments against that post, one for saving likes of posts and last one is to store IP addresses of users. I used IP to save user likes but when you will use it you should use user ID instead of IP so that you can accurately identify that current user already liked or not.

 
CREATE TABLE IF NOT EXISTS `facebook_collapsed_posts` (
  `p_id` int(11) NOT NULL AUTO_INCREMENT,
  `f_name` varchar(50) NOT NULL,
  `post` varchar(255) NOT NULL,
  `f_image` varchar(50) NOT NULL,
  `date_created` int(11) NOT NULL,
  `userip` varchar(200) NOT NULL,
  PRIMARY KEY (`p_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
 
--
-- Dumping data for table `facebook_collapsed_posts`
--
 
INSERT INTO `facebook_collapsed_posts` (`p_id`, `f_name`, `post`, `f_image`, `date_created`, `userip`) VALUES
(2, 'Zeeshan Rasool', 'Facebook style collapsed comments using jQuery, php and mysql.', 'zee.jpg', 1285405523, '');
CREATE TABLE IF NOT EXISTS `facebook_collapsed_likes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `likes` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
 
--
-- Dumping data for table `facebook_collapsed_likes`
--
 
INSERT INTO `facebook_collapsed_likes` (`id`, `likes`, `post_id`) VALUES
(1, 0, 2);
CREATE TABLE IF NOT EXISTS `facebook_collapsed_ip` (
  `userip` varchar(100) NOT NULL,
  `post_id` int(11) NOT NULL
)
CREATE TABLE IF NOT EXISTS `facebook_collapsed_comments` (
  `c_id` int(11) NOT NULL AUTO_INCREMENT,
  `userip` varchar(200) NOT NULL,
  `comments` text NOT NULL,
  `date_created` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  PRIMARY KEY (`c_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
 
--
-- Dumping data for table `facebook_collapsed_comments`
--
 
INSERT INTO `facebook_collapsed_comments` (`c_id`, `userip`, `comments`, `date_created`, `post_id`) VALUES
(1, '', 'Facebook Like URL data Extract Using jQuery PHP and Ajax  http://bit.ly/bYp6qn', 1285424171, 2),
(2, '', 'Facebook Style Wall Posting and Comments System using jQuery PHP and Ajax.  http://bit.ly/df9t1L', 1285417630, 2),
(3, '', 'Facebook Like URL data Extract Using jQuery PHP and Ajax  http://bit.ly/bYp6qn', 1285405523, 2),
(4, '', 'Facebook Style Wall Posting and Comments System using jQuery PHP and Ajax.  http://bit.ly/df9t1L', 1285417630, 2),
(5, '', 'Facebook Style Event Creator With jQuery and Ajax. http://bit.ly/b4pIqc', 1285405523, 2),
(6, '', 'Facebook Style Wall Posting and Comments System using jQuery PHP and Ajax.  http://bit.ly/df9t1L', 1285424171, 2),
(7, '', 'Facebook Style Profile Edit script using jQuery, Ajax and PHP. http://bit.ly/bxREzE', 1285405523, 2),
(8, '', 'Facebook Style Profile Edit script using jQuery, Ajax and PHP. http://bit.ly/bxREzE', 1285424171, 2),
(9, '', 'Facebook Like URL data Extract Using jQuery PHP and Ajax  http://bit.ly/bYp6qn', 1285417630, 2),
(10, '', 'Facebook Style Suggest a Friend Box Using jQuery and PHP. http://bit.ly/a5Y0pA', 1285417630, 2);

JQuery Code

$(document).ready(function(){	
 
	$('.ViewComments').livequery("click",function(e){
 
		var parent  = $(this).parent();
		var getID   =  parent.attr('id').replace('collapsed-','');
 
		var total_comments = $("#totals-"+getID).val();
 
		$("#loader-"+getID).html('<img src="loader.gif" alt="" />');
 
		$.post("view_comments.php?postId="+getID+"&totals="+total_comments, {
 
		}, function(response){
 
			$('#CommentPosted'+getID).prepend($(response).fadeIn('slow'));
			$('#collapsed-'+getID).hide();
 
		});
	});	
 
	/// like 
 
	$('.LikeThis').livequery("click",function(e){
 
		var getID   =  $(this).attr('id').replace('post_id','');
 
		$("#like-loader-"+getID).html('<img src="loader.gif" alt="" />');
 
		$.post("like.php?postId="+getID, {
 
		}, function(response){
 
			$('#like-stats-'+getID).html(response);
 
			$('#like-panel-'+getID).html('<a href="javascript: void(0)" id="post_id'+getID+'" class="Unlike">Unlike</a>');
 
			$("#like-loader-"+getID).html('');
		});
	});	
 
	/// unlike 
 
	$('.Unlike').livequery("click",function(e){
 
		var getID   =  $(this).attr('id').replace('post_id','');
 
		$("#like-loader-"+getID).html('<img src="loader.gif" alt="" />');
 
		$.post("unlike.php?postId="+getID, {
 
		}, function(response){
 
			$('#like-stats-'+getID).html(response);
 
			$('#like-panel-'+getID).html('<a href="javascript: void(0)" id="post_id'+getID+'" class="LikeThis">Like</a>');
 
			$("#like-loader-"+getID).html('');
		});
	});	
 
 
 
});

Like.php

<?php
	include('dbcon.php');
 
	if($_REQUEST['postId'])
	{
		$userip = $_SERVER['REMOTE_ADDR'];
 
		mysql_query("update facebook_collapsed_likes set likes=likes+1 where post_id= ".$_REQUEST['postId']);
 
		mysql_query("INSERT INTO facebook_collapsed_ip (userip,post_id) VALUES('".$userip."','".$_REQUEST['postId']."')");
 
		$total_likes = mysql_query("SELECT * FROM facebook_collapsed_likes where post_id = ".$_REQUEST['postId']." ");
		$likes = mysql_fetch_array($total_likes);
		$likes = $likes['likes'];
	}
	echo $likes;
?>

Unlike.php

<?php
	include('dbcon.php');
 
	if($_REQUEST['postId'])
	{
		$userip = $_SERVER['REMOTE_ADDR'];
 
		mysql_query("update facebook_collapsed_likes set likes=likes-1 where post_id= ".$_REQUEST['postId']);
 
		mysql_query("delete from facebook_collapsed_ip where userip=".$userip." AND post_id = ".$_REQUEST['postId']);
 
		$total_likes = mysql_query("SELECT * FROM facebook_collapsed_likes where post_id = ".$_REQUEST['postId']." ");
		$likes = mysql_fetch_array($total_likes);
		$likes = $likes['likes'];
	}
	echo $likes;
?>

View_comments.php

<?php
include('dbcon.php');
 
function clickable_link($text = '')
{
	$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
	$ret = ' ' . $text;
	$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\" rel=\"no_follow\">\\2</a>", $ret);
 
	$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
	$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
	$ret = substr($ret, 1);
	return $ret;
}
 
$comments = mysql_query("SELECT *,UNIX_TIMESTAMP() - date_created AS CommentTimeSpent FROM facebook_collapsed_comments where post_id = ".$_REQUEST['postId']." order by date_created asc limit 4, ".$_REQUEST['totals']);
 
$comment_num_row = mysql_num_rows(@$comments);
 
if($comment_num_row > 0)
{
	while ($rows = mysql_fetch_array($comments))
	{
		$days2 = floor($rows['CommentTimeSpent'] / (60 * 60 * 24));
		$remainder = $rows['CommentTimeSpent'] % (60 * 60 * 24);
		$hours = floor($remainder / (60 * 60));
		$remainder = $remainder % (60 * 60);
		$minutes = floor($remainder / 60);
		$seconds = $remainder % 60;	?>
 
		<div class="commentPanel" align="left">
			<img src="small.jpg" width="35" class="CommentImg" style="float:left;" alt="" />
			<label class="postedComments">
				<?php  echo clickable_link($rows['comments']);?>
			</label>
			<br clear="all" />
			<span style="margin-left:43px; color:#666666; font-size:11px">
			<?php
 
			if($days2 > 0)
			echo date('F d Y', $rows['date_created']);
			elseif($days2 == 0 && $hours == 0 && $minutes == 0)
			echo "few seconds ago";		
			elseif($days2 == 0 && $hours == 0)
			echo $minutes.' minutes ago';
			elseif($days2 == 0 && $hours > 0)
			echo $hours.' hour ago';
			else
			echo "few seconds ago";	
			?>
			</span>
 
		</div>
	<?php
	}
}?>

Download all the files and use this stylish tutorial. Thanks !

Add To Facebook Stumble This Digg This Add To Del.icio.us Add To Reddit Add To Yahoo Add To Twitter


Written by ZeeShaN

ZeeShaN RasooL is a web developer who loves to work in latest technologies to create more interactive dynamic and beautiful web pages.

  • litomfr

    12345

    February 15 2012
    CommentsLike

    • Itz nice, but voting – me ja rahi hai aur ip kahi save he nahi hota. Is me problem py problem hai.

      January 03 2012
      CommentsLike

      • thanks man.. thousand thanks..
        actually another guy from 9lessons dot info website is has copied your script and modified little bit and he is selling it.

        be opensource everytime like zeeshan is better.. luv it guy

        December 10 2011
        CommentsLike
        • jord

          I found the problem. I had already a different js file on my website. So the livequery wasn’t working with this file . So I remove the insertion js code and it works.

          October 08 2011
          CommentsLike
          • jord

            I get this error Object [object Object] has no method ‘livequery’ . How can I make this work?

            October 06 2011
            CommentsLike

            • once again. Brilliant job. Even though I am new to PHP I have managed to integrate this with the full message system. What an app. Thank you for your kindness in sharing your hard work.

              July 13 2011
              CommentsLike
              • Undercoverr

                Can you tell me how i can get this work?? I change root with my username and friends with my database name but it doesn’t work :(

                June 20 2011
                CommentsLike
                • Deddi

                  One thing it is not doing Zee, it does not delete the userip or post id from the data base when you unlike it, so when you refresh the page, it goes back to unlike instead of like.

                  May 18 2011
                  CommentsLike
                  • test

                    testing

                    nice site!

                    April 15 2011
                    CommentsLike
                    • ZeeShaN

                      @Jeff, thanks for pointing out these things. Usually I work on a idea and give my readers a solution for that but the security and other things which is no doubt much important but I want them to leave on readers. Because we can give a detail a lecture on securing a script and making it efficient with proper querying. So, my first priority is always to give some useful ideas to users. Although, I always try to use proper code but with less time it goes in wrong direction. I apologize this. :)
                      Thanks !

                      December 21 2010
                      CommentsLike









                      Enter your Email:

                      Click Here for Popular

                      Who I Am

                      Zeeshan Rasool

                      Software Engineer - PHP
                      Lahore - Pakistan

                      zeeshan(@)99points.info
                      Skype: zeeshan-rasool
                      gTalk: zishan.rasool85

                      Categories

                      Tags

                      Comments