Top

Follow me and receive all the latest free scripts:

By Email:

Categories
Most Popular Posts

jQuery Facebook Like System

jQuery Facebook Like System

Published October 09, 2014 by , category jQuery

FacebookLike SystemjQueryPHPMySQL

How to create a Facebook Like System using jQuery, PHP & MySQL

Introduction

Here is a very simple jQuery Facebook Like System that can be used to like/unlike a page, an article, a comment...

Enhance your Blog, make your Website more dynamic. I tried to make the code as simple as I can, so you can adapt the system easily. All code lines are commented.

Files architecture

index.php
db.class.php

ajax

tuto-like-page.php

design

jquery

jquery-1.10.1.min.js

js

tuto_like_it.js

Live demo

For a Like System, we need two variables:

  1. $pageId: the id of the page the user wants to Like
  2. $userId: the id of the user (taken from the database, when the user is connected)

In this demo, I simply set up the two variables as follow:

  1. $pageId=1: the current page id is 1
  2. $userId = str_replace('.', '', $_SERVER['REMOTE_ADDR']): to have a unique user id (YOU) I take your current IP address and I remove the "dots". Example: if your IP address is 111.222.333.444, your user id will be 111222333444.

You are logged in as 3.238.8.102. Your id is 32388102.

Database structure

In the tc_tuto_like_page table, I store the page_id, user_id and a like_it bit (0 for "not like" and 1 for "like").

CREATE TABLE IF NOT EXISTS `tc_tuto_like_page` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `page_id` int(6) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `like_it` int(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;

Database connection

Page db.class.php. You put your database access parameters. More information about the database connection I use here.

HTML/PHP code

This is the index.php page (the complete structure), or the page you want to insert the Like System. I include the 4 CSS style lines in this page. You may want to place the CSS style in your style.css file later.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
	<title>Tuto Facebook Like System</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css">
	<style>
		.like_heart a { display: block; background: url("design/icon-heart-32.png") no-repeat; width: 32px; height: 32px }
		.like_heart a:hover { background-position: 0 -32px; width: 32px; height: 32px }

		.like_heart_off a { display: block; background: url("design/icon-heart-off-32.png") no-repeat; width: 32px; height: 32px }
		.like_heart_off a:hover { background-position: 0 -32px; width: 32px; height: 32px }
	</style>
</head>

<body>

<div class="container">
	<div class="row">
		<div class="col-md-12">
		
			<?php
			include('db.class.php');
			$bdd = new db();

			$pageId = 1; // the ID of the current page
			
			$userIP = $_SERVER['REMOTE_ADDR']; // Get User IP address
			$userId = str_replace('.', '', $userIP); // Remove the . "dot" from the IP address to have a unique integer
			
			// Get the like_it field, 0 or 1 to know if user already like the page or not
			// And we check if the database table line exists
			// 0 = don't like
			// 1 = like
			$likeIt = $bdd->getOne('SELECT like_it FROM tc_tuto_like_page WHERE page_id='.$pageId.' AND user_id='.$userId.'');
			?>
			<p>You are logged in as <b><?php echo $userIP; ?></b>. Your id is <b><?php echo $userId; ?></b>.</p>
			
			<table><tr>
				<!--
				If the like_it field is at 0 or if the $likeIt request is empty
				class="like_heart" (we display icon-heart-32.png icon)
				else
				class="like_heart_off" (we display icon-heart-off-32.png icon)
				-->
				<td><div class="<?php if ($likeIt['like_it']==0 || empty($likeIt)) echo 'like_heart'; else echo 'like_heart_off'; ?>" id="likeIt" rel='{"userId": <?php echo $userId; ?>,"pageId": <?php echo $pageId; ?>}'><a href="#"></a></div></td>
				<td style="padding-left: 10px"><div id="box"></div></td>
			</tr></table>
			
		</div>
	</div>
</div>

<script type="text/javascript" src="jquery/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="js/tuto_like_it.js"></script>
	
</body>
</html>

PHP code

It's the ajax/tuto-like-page.php file, called by the Ajax function for data treatment.

<?php
include('../db.class.php');
$bdd = new db();

if($_POST) {
	$userId = $_POST['userId'];
	$pageId = $_POST['pageId'];
	
	$likeIt = $bdd->getOne('SELECT * FROM tc_tuto_like_page WHERE page_id='.$pageId.' AND user_id='.$userId.''); // We test if the line exists in the database table
	if (empty($likeIt)) { // If not, we create the line with the current page_id and user_id, the like_it field will be at 1 (like)
		$addUser = $bdd->execute('INSERT INTO tc_tuto_like_page (page_id, user_id, like_it) VALUES ('.$pageId.', "'.$userId.'", 1)');
		$callBack = "like_heart_off"; // We send back like_heart_off, so the button will be replaced by icon-heart-off-32.png
	} else { // if the line exists
		if ($likeIt['like_it'] == 0) { // if the like_it field was at 0 (not like)
			$likeBit = 1; // then we pass it at 1 (like)
			$callBack = "like_heart_off"; // We send back like_heart_off, so the button will be replaced by icon-heart-off-32.png
		} else { // if the like_it field was at 1 (like)
			$likeBit = 0; // then we pass it at 0 (not like)
			$callBack = "like_heart"; // We send back like_heart, so the button will be replaced by icon-heart-32.png
		}
			
		$update = $bdd->execute('UPDATE tc_tuto_like_page SET like_it='.$likeBit.' WHERE page_id='.$pageId.' AND user_id='.$userId.''); // we update the new like_it
	}
	
	echo $callBack;
}
?>

jQuery code

It's the tuto_like_it.js file.

$(function() {
	var state = $('div#likeIt').attr('class'); // We get the class attribut of div="likeIt"
	if (state == "like_heart") { // If the class="like_heart"
		$('div#likeIt a').attr('title', 'Like this page'); // We add a title="Like this page" to the <a href="">...
		$('#box').text('Like'); // We add a "Like" text inside <div="box"></div>
	} else { // If the class="like_heart_off"
		$('div#likeIt a').attr('title', 'Unlike this page'); // We add a title="Unlike this page" to the <a href="">...
		$('#box').text('You like it'); // We add a "You like it" text inside <div="box"></div>
	}
	
	$('div#likeIt').on('click', function buttonLike(event) { // When click on the icon
		$(event.target).off("click", buttonLike); // Disable click event
		$("#box").html('<img src="/design/loader-small.gif" alt="" />'); // Display a processing icon
		var relData = $.parseJSON($(this).attr('rel')); // Get Json from rel attribute: the userId and the pageId
		
		var data = {'userId': relData.userId, 'pageId': relData.pageId}; // Create the data which will be send via Ajax
		
		$.ajax({ // JQuery Ajax
			type: 'POST',
			url: '/ajax/tuto-like-page.php', // URL to the PHP file which will insert new value in the database
			data: data, // We send the data string
			timeout: 3000,
			success: function(data) {
				$('div#likeIt').attr('class', data); // Depending of the data string returned (like_heart OR like_heart_off)...
				if (data == "like_heart") {
					$('div#likeIt a').attr('title', 'Like this page'); // We change values for the <a title="">
					$('#box').text('Like'); // and for the <div id="box">
				} else {
					$('div#likeIt a').attr('title', 'Unlike this page'); // Same
					$('#box').text('You like it'); // Same
				}
			},
			error: function() {
				$('#box').text('Problem');
			}
		});
		
		$(event.target).on("click", buttonLike); // Click event is allowed again
		
		return false;
	});
});

Conclusion

That's it for today, simple and efficient. Don't hesitate to use the comments below if you have any problem implementing the code. Happy coding!

In a next tutorial I will make a jQuery Voting System (YouTube like Voting System).

About Simon Laroche
Simon Laroche on Google+
Simon Laroche on Twitter
Simon Laroche on Facebook
Simon Laroche on Pinterest
Simon Laroche on LinkedIn
: I am a Coder, Designer, Webmaster and Expert SEO Consulting, I'm also a wise traveller and an avid amateur photographer. I created the website TipoCode and many others such as Landolia: a World of Photos...

If you need help about this script, please leave a comment below. I reply as much as I can depending of my time, you may also get help from others.
I also offer a paid support, if you are in the need to adapt or create a script...

Comments (6 comments)

Simon Laroche
Simon Laroche Posted on February 29, 2016
@David: if you get only the loading icon it means something is wrong somewhere. I think first you have to check if you get the variables $userId and $pageId in the REL attribute. So also check if all MySQL queries are running. To do that comment some part of the code and place some echo ''; in your code.
Also you have to test the jQuery code. To do that place some alert(variable); somewhere in your code to check if you get the REL attribute and others...
There is just an error somewhere, the hard thing is to find where, which is not so hard if you proceed like I said, you can find out where is the missing variable or if they are sent to jQuery properly.
Also be sure your MySQL queries are correct! Most of the time when variables are sent by AJAX for treatment, if queries are wrong, nothing is sent back, so the loading remains and the tank is not replaced with the correct new content.
David Posted on February 28, 2016
Hey man,

I'm encountering some difficulty with your code. I'm not sure if that's the main issue though.
rel="{'userId': <?php echo $userId; ?>,'pageId': <?php echo $pageId; ?>}"

This is used to parse the data into ajax and send it to another page. I think it doesn't do anything. It tells me it is an unknown attribute.
I have used your code as a base for my system like this as this is the best solution for what I want to achieve. However the best I could get is the loading icon moving.
I have tried copying your code just to test it but it didn't work neither.
Got any idea what might be the issue here? It doesn't ad anything to the database and only displays the moving loading icon.
I really love this tutorial though and I hope to use it as well. Cheers!
addzifi Posted on February 28, 2016
i have do your tutorial but why the page is blank?
Simon Laroche
Simon Laroche Posted on October 05, 2015
@Juanpa144: I guess you mean this line?
url: '/ajax/tuto-like-page.php',

It works for me but yes you are right people may need to remove a "/" and write
url: 'ajax/tuto-like-page.php',


Thank you
Juanpa144 Posted on October 05, 2015
How can i place the total likes next to the icon, and make it change when somebody click like it or unlike it?
Juanpa144 Posted on October 05, 2015
Excelent tutorial, thanks a lot, there is a little problem, in tuto_like_it.js file, when you call the ajax url, i find an extra "/", so the function return "problem", maybe can be confused for other users.

Thanks again!