In this tutorial we will create a simple 5 star rating system using jQuery, MySQL, PHP and AJAX. We will use jQuery to highlight the star the mouse is over and the preceding stars, AJAX to send the vote to the server, PHP to process the vote and MySQL to store the vote.
The basic idea
This rating system will be able to highlight half-stars, too. Doing this using only CSS would be difficult, so we will use instead different background images for each possibility, and on mouse-over we will just change the background image. In this case appears an another problem: on changing the background we should wait for the new image to load, so instead of having a lot of different images we will combine the images in a single image and on mouse-over we will change the background position.We will use this image:
ratings.png

And here is and example about how we will highlight the stars:

Step1: The HTML and CSS part
We`re going to create first a rating without votes (no stars highlighted, 0 votes, 0 rating):Here is the HTML:
<div class="star-rating" id="rating1result0">
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
<div class="result">
<span style="color:green">0</span> (0)
</div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
<div class="result">
<span style="color:green">0</span> (0)
</div>
And here is the CSS:
.star-rating {
width:80px;
height:16px;
float:left;
background:url(ratings.png);
cursor:pointer;
}
.star {
width:16px;
height:16px;
float:left;
}
.result {
float:left;
height:16px;
color:#454545;
margin-left:5px;
line-height:110%;
}
width:80px;
height:16px;
float:left;
background:url(ratings.png);
cursor:pointer;
}
.star {
width:16px;
height:16px;
float:left;
}
.result {
float:left;
height:16px;
color:#454545;
margin-left:5px;
line-height:110%;
}
The id of the first div (star-rating) is made of 2 parts:
rating1 - this represents the id number of the rating system, if you want to use the rating system for more items than you will need to assign an unique id number to each item (e.g.: rating2, rating3, ... rating999)
result0 - this represents the starting value, in our case 0 is the result of the votes (we will change this value later in this tutorial using PHP)
rating1 - this represents the id number of the rating system, if you want to use the rating system for more items than you will need to assign an unique id number to each item (e.g.: rating2, rating3, ... rating999)
result0 - this represents the starting value, in our case 0 is the result of the votes (we will change this value later in this tutorial using PHP)
The above code should result something like this:

Step 2: The jQuery part
Now we`re going to write a script to highlight the star the mouse is over and preceding stars. We will do this by changing the background-position property (see the second image):And here is the jQuery code:
$('.star').mouseover(function (){
var star = $(this).index() 1;
$(this).parent().css("background-position","0 -" (32 * star) "px");
});
$('.star-rating').mouseout(function (){
var originalresult = $(this).attr('id').split('result')[1];
$(this).css("background-position","0 -" (32 * originalresult) "px");
});
var star = $(this).index() 1;
$(this).parent().css("background-position","0 -" (32 * star) "px");
});
$('.star-rating').mouseout(function (){
var originalresult = $(this).attr('id').split('result')[1];
$(this).css("background-position","0 -" (32 * originalresult) "px");
});
This should result something like this:

Step 3: The MySQL part
At this step we need to create a MySQL table to store the votes. We will need 2 columns:id - the id of the rating system
rating - the selected stars number (from 1 to 5)
You can create this table from your phpMyAdmin control panel or by simply running this PHP code (don`t forget to replace the password and username to yours):
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("CREATE TABLE ratings(
id MEDIUMINT UNSIGNED,
rating tinyint
)") or die(mysql_error());
echo "Table Created!";
mysql_select_db("database") or die(mysql_error());
mysql_query("CREATE TABLE ratings(
id MEDIUMINT UNSIGNED,
rating tinyint
)") or die(mysql_error());
echo "Table Created!";
Step 4: AJAX and PHP
When we talk about AJAX we talk about making a request to the server to run a PHP file. This request is sent via jQuery. When a star is clicked (somebody want`s to vote) we need to tell the server to save the vote in the MySQL table, but we also need to send the id and the selected rating to the server.We`re going to make a request to the save-vote.php file (we will create this file later) and we will send the id of the rating system and the vote using the post method.
Here is the code:
$('.star').click(function (){
var id = $(this).parent().attr('id').split('rating')[1];
var vote = $(this).index() 1;
$.ajax({
type: "POST",
url:"save-vote.php",
data: "id=" id "(and)vote=" vote
});
});
//replace (and) with the "and" sign - parsing error...
var id = $(this).parent().attr('id').split('rating')[1];
var vote = $(this).index() 1;
$.ajax({
type: "POST",
url:"save-vote.php",
data: "id=" id "(and)vote=" vote
});
});
//replace (and) with the "and" sign - parsing error...
Now we need to create the save-vote.php file. This file will insert the new vote into our MySQL table:
mysql_connect('localhost','username','password');
mysql_select_db('database');
$id = intval($_POST['id']);
$vote = intval($_POST['vote']);
mysql_query("INSERT INTO ratings (id,rating) VALUES(" . $id . "," . $vote . ")") or die(mysql_error());
mysql_select_db('database');
$id = intval($_POST['id']);
$vote = intval($_POST['vote']);
mysql_query("INSERT INTO ratings (id,rating) VALUES(" . $id . "," . $vote . ")") or die(mysql_error());
Step 5: Show the results on loading
At the first step we built the basic HTML of the rating system, but this can will display 0 votes every time the rating system is loaded. Now that we have a MySQL table with votes we need to make the rating system to show the ratings results based on the votes from the MySQL table right from the moment when it loads. To do this we just need to add some PHP to our HTML code:<?php
mysql_connect('localhost','username','password');
mysql_select_db('databse');
$votes = mysql_query("SELECT rating FROM ratings WHERE id = 1");
$votesnr = 0;
$totalvotes = 0;
while($vote = mysql_fetch_array($votes)){
$votesnr ;Â
$totalvotes = $vote['rating'];
}
if($votesnr == 0){
$rating = 0;
}
else {
$rating = $totalvotes/$votesnr;
}
$roundedrating = floor($rating) round($rating - floor($rating))/2;
?>
<div class="star-rating" id="rating1result<?php echo $roundedrating; ?>" style="background-position:0 -<?php echo $roundedrating * 32; ?>px;">
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
<div class="result">
<span style="color:green"><?php echo round($rating,2); ?></span> (<?php echo $votesnr; ?>)
</div>
mysql_connect('localhost','username','password');
mysql_select_db('databse');
$votes = mysql_query("SELECT rating FROM ratings WHERE id = 1");
$votesnr = 0;
$totalvotes = 0;
while($vote = mysql_fetch_array($votes)){
$votesnr ;Â
$totalvotes = $vote['rating'];
}
if($votesnr == 0){
$rating = 0;
}
else {
$rating = $totalvotes/$votesnr;
}
$roundedrating = floor($rating) round($rating - floor($rating))/2;
?>
<div class="star-rating" id="rating1result<?php echo $roundedrating; ?>" style="background-position:0 -<?php echo $roundedrating * 32; ?>px;">
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
<div class="result">
<span style="color:green"><?php echo round($rating,2); ?></span> (<?php echo $votesnr; ?>)
</div>
Step 6: Update the results on voting
At this, last step we will edit the rating system in a way that when somebody votes, the voted star and the preceding stars will be highlighted and the user will not be able to vote again until the page is refreshed.To do this we will need to edit the jQuery code from step 4:
$('.star').click(function (){
var id = $(this).parent().attr('id').split('rating')[1];
var vote = $(this).index() 1;
$.ajax({
type: "POST",
url: "save-vote.php",
data: "id=" id "(and)vote=" vote
});
$(this).parent().removeAttr("id");
$(this).parent().html(" ");
});
var id = $(this).parent().attr('id').split('rating')[1];
var vote = $(this).index() 1;
$.ajax({
type: "POST",
url: "save-vote.php",
data: "id=" id "(and)vote=" vote
});
$(this).parent().removeAttr("id");
$(this).parent().html(" ");
});
Conclusion
As you see the trick is done in just 2 lines of code. The first line removes the id from the star-rating div, and without an id the code from step 2 is not triggered on mouse-out, so the star remains highlighted.In the second line we delete those 5 divs with class star so again the code from step 2 is not triggered without the class star.
This is a very simple and easy to hack voting system, but it`s just good for a simple item rating or for a blog. This system needs to be installed on a php page to work. This is not the best star rating system, but it`s good for a start. Thanks for reading!
Jquery ajax json
Posted 234 days ago.Hello there! I just now desired to uncover you have any issues with online criminals?
My previous weblog (live journal) appeared to be compromised we ended up
being shedding almost a year involving working hard
because of simply no back up. Are there any ways of avoid hackers?
My previous weblog (live journal) appeared to be compromised we ended up
being shedding almost a year involving working hard
because of simply no back up. Are there any ways of avoid hackers?
usman
Posted 238 days ago.Hi:
I have a problem with the variable where you initialize votesnr variable within the while loop as `$votesnr ;Â ` it gives an error of `Â`.Is there any other value which i can use instead of this `Â`.
I have a problem with the variable where you initialize votesnr variable within the while loop as `$votesnr ;Â ` it gives an error of `Â`.Is there any other value which i can use instead of this `Â`.
aris
Posted 240 days ago.I have fixed some error in code checkthis
docs . google . com/open?id=0B-FNXt0__Sb6cy1ZME8yYUJRdk0
docs . google . com/open?id=0B-FNXt0__Sb6cy1ZME8yYUJRdk0
leonsss
Posted 244 days ago.Did anybody figure out how does the jQuery work?
Everythins ellse works fine
Everythins ellse works fine
Rockit
Posted 257 days ago.$roundedrating = floor($rating) round($rating - floor($rating))/2;
The space between floor($rating) and round(... gets error. Which symbol we need to use?
Good tutorial, regards.
The space between floor($rating) and round(... gets error. Which symbol we need to use?
Good tutorial, regards.
Flyman
Posted 253 days ago.I used this function (wrote by Glann) and worked fine...
I had a problem with the id attr appears undefined. ideas?
I had a problem with the id attr appears undefined. ideas?
googlepo
Posted 278 days ago.This is the second entry I read tonight. And I am on my third. Got to think which one is next. Thank you.
Glenn
Posted 320 days ago.I found this solution for the JQuery.
$(function(){
$(`.star`).mouseover(function (){
var star = $(this).index()+1;
var x =(32 * star);
$(this).parent().css(`backgroundPosition`,`0% ` +(-x)+ `px`);
});
$(`.star-rating`).mouseout(function (){
var originalresult = $(this).attr(`id`).split(`result`)[1];
var y =(32 * originalresult);
$(this).css(`background-position`,`0%` +(-y)+ `px`);
});
});
Works like a charm :)
$(function(){
$(`.star`).mouseover(function (){
var star = $(this).index()+1;
var x =(32 * star);
$(this).parent().css(`backgroundPosition`,`0% ` +(-x)+ `px`);
});
$(`.star-rating`).mouseout(function (){
var originalresult = $(this).attr(`id`).split(`result`)[1];
var y =(32 * originalresult);
$(this).css(`background-position`,`0%` +(-y)+ `px`);
});
});
Works like a charm :)
Kevin Nobert
Posted 325 days ago.Hi Guys ..
I like this Tutorial ..Its a simple and good tutorial ...I like it ...
But i found some problems in the Jquery ...the Jquery script is not working for me ...I just rewrite the jquery to Like this
I like this Tutorial ..Its a simple and good tutorial ...I like it ...
But i found some problems in the Jquery ...the Jquery script is not working for me ...I just rewrite the jquery to Like this
Pratik
Posted 297 days ago.can u please send me the jQuery part, its not visible on the reply post u have given. the above given jQuery wont work
KSC
Posted 363 days ago.If i want to include 5 x of this star in the same page . like for example different categories of question
Reliability
-Stars-
Service
-Stars
Popularity
-Stars
Efficiency
-Stars
How can i include it ?
Reliability
-Stars-
Service
-Stars
Popularity
-Stars
Efficiency
-Stars
How can i include it ?
Csabi
Posted 363 days ago.Hi!
I think the simplest way would be to create a different mysql table and save-vote file for each of the categories.
So you would have save-vote-popularity.php with the table popularity_ratings and you should repeat the code from step 5 after each of the rating systems on your page, but using the proper mysql database.
I think the simplest way would be to create a different mysql table and save-vote file for each of the categories.
So you would have save-vote-popularity.php with the table popularity_ratings and you should repeat the code from step 5 after each of the rating systems on your page, but using the proper mysql database.
viorel
Posted 389 days ago.unexpected round on php read vote.
i use .round and netbeens say is ok
next the star wonth show up ,
i want this sistem is simple and ideal for my website , but i newer work with ajax or javascript so i dont now what to do , help..
i use .round and netbeens say is ok
next the star wonth show up ,
i want this sistem is simple and ideal for my website , but i newer work with ajax or javascript so i dont now what to do , help..
Yak
Posted 394 days ago.Step 2, the jQuery part won`t work for me. Can you please tell us the link between the files we make in this tutorial?
Csabi
Posted 394 days ago.The jQuery code from the second step does not communicate with other files, it just highlights the stars if you move your mouse over the stars and it highlights the stars back to the original state when you move the mouse away.
The 5 star rating system is made of 2 files:
- the page where the star rating is located
- and the save-vote.php page, this is contacted using AJAX to save the votes
The 5 star rating system is made of 2 files:
- the page where the star rating is located
- and the save-vote.php page, this is contacted using AJAX to save the votes
Csabi
Posted 395 days ago.I`we wrote the tutorial a long time ago, I don`t have the page...
But the structure is:
<html>
<head>
The CSS part
</head>
<body>
The php part
The ajax part
</body>
</html>
But the structure is:
<html>
<head>
The CSS part
</head>
<body>
The php part
The ajax part
</body>
</html>


27 comments so far:
LEAVE A COMMENT