Top

Follow me and receive all the latest free scripts:

By Email:

Categories
Most Popular Posts

Youtube like voting system with jQuery, PHP and MySQL

Youtube like voting system with jQuery, PHP and MySQL

Published November 03, 2014 by , category jQuery

YoutubeVoting SystemjQueryPHPMySQL

Voting system similar to YouTube like & dislike button, which can be applied to any content.

Introduction

This tutorial will learn about how to create a cookie based like / dislike voting system using jQuery, PHP and MySQL. When a user votes, a one-day live cookie is placed on his computer which prevents him to vote again before the next day. You can change the life of the cookie.

You can install one voting system per page, containing any kind of media you want the user vote for. Two counters indicate the number of like and dislike vote.

Files architecture

index.php
db.class.php

ajax

tuto-yt-voting-system.php

jquery

jquery-1.10.1.min.js

js

tuto-yt-voting-system.js

Design

Live demo

Click on the thumbs up or thumbs down icon to like or dislike the page. You can vote one time per day.

2233
657

Database structure sample

I called the database table tc_tuto_yt_voting_system. id is the "id" (database row number). page_id is the id of the page where you install the voting system. You must create a new line with a page_id every time you install the voting system in a page (this may be done automatically of course!). positive is the like counter vote number. negative is the dislike counter vote number.

CREATE TABLE IF NOT EXISTS `tc_tuto_yt_voting_system` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `page_id` int(6) NOT NULL,
  `positive` int(6) NOT NULL DEFAULT '0',
  `negative` int(6) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;

INSERT INTO `tc_tuto_yt_voting_system` (`id`, `page_id`, `positive`, `negative`) VALUES
(1, 5, 59, 29);

Database connection

Page db.class.php. More information about the database connection I use here. But I guess you already have yours .

HTML & PHP code

This is the index.php page (or any page you want the script appears). All lines are commented.

There is a rollover on the thumbs up and thumbs down icons. All the code and style are included here but if you want more information about image rollover without preload, check this tutorial.

<?PHP
include('db.class.php'); // Database connection
$bdd = new db();
?>
<!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>Youtube like Voting 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">

	<script type="text/javascript" src="jquery/jquery-1.10.1.min.js"></script>
	
	<style>
	.vote_up a { display: block; background: url("design/vote-up.png") no-repeat; width: 22px; height: 19px; }
	.vote_up a:hover { background-position: 0 -19px; width: 22px; height: 19px; }
	.vote_up_done { display: block; background: url("design/vote-up-done.png") no-repeat; width: 22px; height: 19px; }
	.vote_down a { display: block; background: url("design/vote-down.png") no-repeat; width: 22px; height: 19px; }
	.vote_down a:hover { background-position: 0 -19px; width: 22px; height: 19px; }
	.vote_down_done { display: block; background: url("design/vote-down-done.png") no-repeat; width: 22px; height: 19px; }
	
	#lineBlock div.oneLine { display: inline-block; vertical-align: middle; }
	
	.number { color: #333; font-size: 12px; }
	.numberVoted { color: #9a9a9a; font-size: 12px; }
	</style>
</head>

<body>

<div class="container">
	<div class="row">
		<div class="col-md-12">
		
		<hr></hr>
		
		<?php
		$pageId = 5; // current ID page here (5 is a random example)
		
		$cookie_name = 'tcYtVotingSystem'.$pageId; // Set up the cookie name
		
		$value = $bdd->getOne('SELECT * FROM tc_tuto_yt_voting_system WHERE page_id='.$pageId); // BDD query, page ID values
		?>
		
		<div id="lineBlock">
		<?php if (isset($_COOKIE[$cookie_name])) { ?>
		<div class="vote_up_done oneLine"></div><div class="numberVoted oneLine"><?php echo $value['positive']; ?></div>
		<?php } else { ?>
		<div class="vote_up oneLine" id="voteUp"><a href="#" onclick="vote('positive', '1', <?php echo $pageId; ?>); return false;" title="I like this"></a></div><div class="number oneLine" id="positive"><?php echo $value['positive']; ?></div>
		<?php } ?>
		
		
		<?php if (isset($_COOKIE[$cookie_name])) { ?>
		<div class="vote_down_done oneLine"></div><div class="numberVoted oneLine"><?php echo $value['negative']; ?></div>
		<?php } else { ?>
		<div class="vote_down oneLine" id="voteDown"><a href="#" onclick="vote('negative', '1', <?php echo $pageId; ?>); return false;" title="I dislike this"></a></div><div class="number oneLine" id="negative"><?php echo $value['negative']; ?></div>
		<?php } ?>
		
		</div>
		
		<span id="message"></span>
		</div>
	</div>
</div>

<script type="text/javascript" src="js/tuto-yt-voting-system.js"></script>
	
</body>
</html>

JS code

jQuery JavaScript Library code. This is the tuto-yt-voting-system.js file. All lines are commented.

jQuery code is triggered when user clicks thumbs up or thumbs down icon. Three values are sent via an Ajax request to tuto-yt-voting-system.php: the value positive or negative depending if the user clicked on thumbs up or thumbs down, the value 1 (positive or negative vote counter is incremented by 1), and the page Id value (here the page Id example is 5).

function vote(type, value, pageId) {
	var dataFields = {'type': type, 'value': value, 'pageId': pageId}; // We pass the 3 arguments, type: positive or negative ; value=1 ; pageId: here 5
	$.ajax({ // Ajax
		type: "POST",
		url: "ajax/tuto-yt-voting-system.php",
		data: dataFields,
		timeout: 3000,
		success: function(dataBack){
			$('#' + type).html(dataBack); // Change the new value in id="positive" or id="negative" DIV
			$('#voteUp').attr('class', 'vote_up_done oneLine'); // Change image by design/vote-up-done.png grey icon
			$('#voteDown').attr('class', 'vote_down_done oneLine'); // Change image by design/vote-down-done.png grey icon
			$('#positive').attr('class', 'numberVoted oneLine'); // Change the number's color by a grey one for the "positive" DIV
			$('#negative').attr('class', 'numberVoted oneLine'); // Change the number's color by a grey one for the "negative" DIV
			$('#message').html('<div id="alertFadeOut" style="color: green">Thank you for voting</div>'); // Diplay message with a fadeout
			$('#alertFadeOut').fadeOut(1000, function () {
				$('#alertFadeOut').text('');
			});
			},
		error: function() {
			$('#message').text('Problem!');
		}
	});
}

PHP code

This is the tuto-yt-voting-system.php file called by JS file Ajax function. All lines are commented.

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

if($_POST) {
	$type = $_POST['type'];
	$value = $_POST['value'];
	$pageId = $_POST['pageId'];
	
	$query = $bdd->execute('UPDATE tc_tuto_yt_voting_system SET '.$type.' = '.$type.' + 1 WHERE page_id='.$pageId);
	
	$value = $bdd->getOne('SELECT '.$type.' FROM tc_tuto_yt_voting_system WHERE page_id='.$pageId); // Get the new number value
	
	$expire = 24*3600; // 1 day
	setcookie('tcYtVotingSystem'.$pageId, 'voted', time() + $expire, '/'); // Place a cookie
	
	echo $value[$type];
}
?>

Conclusion

You might also like the jQuery Facebook Like System tutorial or the Dynamic Voting System with jQuery, PHP and MySQL which are very similar tutorials.

Leave comments below if you need help, or if you find better way to do things.

Happy coding!

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 (33 comments)

arpan Posted on August 02, 2018
When I click lke or unlike button, the count increase in DB table, but in my page its showing "Problem!" but when i refresh my page then its showing the updated count. Please help.
Akash Solanki Posted on December 21, 2017
This is not working. I can like or dislike this in different browsers at same time and your are saying 1 like or dislike per day. Please Solve this problem.
John Posted on December 03, 2017
Thank you, I have implemented this into my page: http://www.mypubspace.com/stl

but I have a small problem, when I click on say the 7th item thumbs up or the 9th item or the 3rd item, it's always the 1st item one that looks like it gets another vote, although when the page has been reloaded everything is ok
mr maker Posted on October 09, 2017
good effort
Simon Laroche
Simon Laroche Posted on September 29, 2016
@Merfin: no I don't have example right now, but easy to adapt in fact.
Merfin Posted on September 29, 2016
Do you have any examples of how this can be used in a user system instead of using cookies? Would be perfect for my project
Simon Laroche
Simon Laroche Posted on August 27, 2016
@zhidr: well I can't explain that in a few words and you will need a complete tutorial. But you can try to do it if you have PHP, MySQL and jQuery knowledge. If you don't have any knowledge to do it then you may contact me to get a quotation. I will have to think about that and the price, maybe 2 days of work.
zhidr Posted on August 27, 2016
Well I was wondering if possible you could tell me how to go about that, Thank you
Simon Laroche
Simon Laroche Posted on August 27, 2016
@zhidr: yes of course, you just need to adapt the script.
zhidr Posted on August 26, 2016
Is there any way that I can use this system with user accounts pull from a database to allow voting besides cookies?
Simon Laroche
Simon Laroche Posted on April 18, 2016
@fares: it's because your link to jquery or js file is broken.
Check all your links.
fares Posted on April 18, 2016
hello
every thing is ok with me
all content appear at the screen
but when i press like or unlike it does not make a change
at the screen or the database, why ???

the single effect is the url of the web page changed from
../index.php
to this
../index.php#
Simon Laroche
Simon Laroche Posted on January 26, 2016
@Tom: you can try to look how I did on the Star Rating System here, or the Dynamic Voting System here.
You can install as many rating system as you want per page. It is the same process.
Tom Posted on January 25, 2016
How do I add voting on multiple products on the same page?

I've tried to edit the code but nothings working.

Anyone have a snippet?
mohx62
mohx62 Posted on October 15, 2015
hi
please put all files in one zip file
thanks
Simon Laroche
Simon Laroche Posted on September 09, 2015
@hind: sorry I can't do anything without code. You just have to correct the mistakes and check your error messages. If you install it like I said it will work except if there is a conflict or something else with your code...
hind Posted on September 08, 2015
thank you very much
but when i executed the index.php that result two number do not appear the image ,don't appear process for voteing
Please helping me
hind Posted on September 07, 2015
thank you master
but when execute the index.php that reasult nothing
Simon Laroche
Simon Laroche Posted on September 07, 2015
@hind
Please adapt db.class.php with your database parameters:
The database name is whatever you want!


$this->host = 'localhost'; //hostname
$this->user = 'user'; //username
$this->password = 'pass'; //password
$this->baseName = 'dbname'; //name of your database
hind Posted on September 06, 2015
this include('db.class.php'); // Database connection
that wrong when execute the programming index.php
hind Posted on September 06, 2015
Please I want name of database is the name same the name table
Nuno Posted on August 17, 2015
Brilliant tutorial, thank you very much for help. Nuno.
Simon Laroche
Simon Laroche Posted on August 08, 2015
$pageId = $_GET['q']

I guess...
Niklas Posted on August 07, 2015
hello

Great script.
But i have a little problem, i get my links by :

questions.php?q=$question->id


How do i add that to your script.
$pageId = 5; // current ID page here (5 is a random example)


Hope you have a ideé...
Jason Posted on July 08, 2015
@Simon Laroche, Thank's for the answer. Yes, I want to adapt this script to my site where I have images. Then on every next page will be new ID of image. So I've made on the very first vote for this ID to make INSERT into the table and right after UPDATE that row with the value of vote - positive or negative.

Thank's for the great tutorial and system.
Simon Laroche
Simon Laroche Posted on July 07, 2015
@Jason: the voting system comment is made for existing pages or products!
Means you HAVE already something (a page -> so an ID) you want people vote for.

Means that when you create a new page, you also create a new LINE in the table tc_tuto_yt_voting_system (name it as you want), and then it's a UPDATE:

$query = $bdd->execute('UPDATE tc_tuto_yt_voting_system SET '.$type.' = '.$type.' + 1 WHERE page_id='.$pageId);


HOWEVER, you are also right, if you want, what you can do is
1) You check the "tc_tuto_yt_voting_system" table
2) If the row with the page/product ID exists you do an UPDATE, if the row doesn't exists or has not been create before, you do an INSERT

You are free to adapt to your needs :)
Jason Posted on July 07, 2015
I don't see INSERT statement for new pageID.. I mean if I open pageID=1 how would save the vote there?
Simon Laroche
Simon Laroche Posted on July 03, 2015
@grs : return false; so there is no page refreshment
Did you install the script exactly same as mine first to see if it works, and start working from my version?

Don't forget to use the same database connection system than mine with the db.class.php file
Explanations here http://www.tipocode.com/database/mysql-php-oop-database-connection/

OR

Use your database connection system (simple MySQL queries for example) but replace my queries by yours.
grs Posted on July 03, 2015
sir, i have 2 questions:

1. what the return false; part is used for?
2. i can not update the database successfully
Simon Laroche
Simon Laroche Posted on February 18, 2015
Also did you add the file db.class.php that you can find here:
http://www.tipocode.com/database/mysql-php-oop-database-connection/
Simon Laroche
Simon Laroche Posted on February 18, 2015
@qwe
Do you use exactly the same database connection as mine?
Do you use wampServer?
I can't tell like that but zip your pages and send me all here:
webmaster at 1two.org
...and I will have a look
qwe Posted on February 17, 2015
i'm new and I need help

I copied all this, but give me a error report
problem is on index.php, line 3
that is this code
$bdd = new db();

why?
Abdou Posted on January 25, 2015
thanksssssssss