Ajax Star Rating February 18, 2007 50 Comments
After reviewing the CSS for a star rating system at komodomedia.com, I decided to make my own star rating system using AJAX. There are a few out there, one is another really good one created by Ryan Masuga over at www.masugadesign.com. I really could have just used his, but oh no, I needed to challenge myself – and I wanted to add feature or two. After a few days I came up with my own unobtrusive ajax star rating system.
Sites Using It
- http://www.rockmodelagency.com/
- http://www.ticosland.com/
- http://www.myspacespells.com/
- http://www.vruuum.com
- http://www.comedytube.nl
- http://www.anachrony.net/
- http://www.gurudaq.com/
- http://www.capeinfo.com/
- http://www.dateyourzippo.com/
If you use this script please send me an email (jordan at boedesign dot com) and I’ll put a link to your site on this page.
NEW VERSION: 1.7 – Updated May 21, 2008

Bug Fixes in v1.7
- Fixed ratings appearing in the correct order. Order by highest rated AND most ratings. (Sebastians Comment)
Features
- Non-obtrusive (works with javascript disabled)
- Does not allow multiple votes – checks against IP and cookies
- Tested in IE 6, IE 7, Firefox 2.x, Opera and Safari
- Pre-loads all images
- Easily style text using the stylesheet
- Precise rating to a 2 decimal place
- Automatically pull top rated based on a custom number – NEW!
- Ability to set ‘novote’ option in the function to not allow users to vote (same thing as static)
- Checks not only against IP upon vote but now includes a cookie check
- Display rating information you want using true or false
- Show rating out of 5
- Show rating in percentage format
- Show number of votes
Installation
Open up includes/rating_config.php and change the mysql database connection info:
$server = 'localhost'; // Database server (default localhost) $dbuser = 'user'; // Database user $dbpass = 'pass'; // Database pass $dbname = 'test'; // Database Name
Now upload the files/directories to your web server. I have named all files
with the prefix "rating_" to not clash with your other files.
You will need to create the necessary tables for the rater. You can either run "create_ratings_table.php" OR paste the following SQL into your phpMyAdmin.
CREATE TABLE `ratings` ( `id` int(11) NOT NULL AUTO_INCREMENT, `rating_id` int(11) NOT NULL, `rating_num` int(11) NOT NULL, `IP` varchar(25) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Usage
The following 3 lines must be on your page.
include("includes/rating_functions.php");
<link href="css/rating_style.css" rel="stylesheet" type="text/css" media="all"> <script type="text/javascript" src="js/rating_update.js"></script>
Now to call the rating stars to display on your page, simply add:
echo pullRating(35,false,false,false,NULL);
Param 1: 35 would be your unique rating id (usually people put $_GET['id'] in there)
Param 2: The first false statement is if you want it to show the rating out of 5.
Example: 3/5. Change this to true if you want to display the rating.
Param 3: The second false statement is if you want to show the rating in percentage format.
Example (50%). Change this to true if you want to display the percentage.
Param 4: The last false statement if if you want to display the total amount of votes
Example (23 Votes). Change this to true if you want to display the amount of votes.
Param 5: The last statement is if you want it to be static (no one can vote) or if you want people to be allowed to vote. NULL is the default but if you only want logged in users to vote then you can change this to ‘novote’. If you’ve used Ryan Masuga’s star rating system then you’ll find this does the same thing as ‘static’.
Getting the top rated items
This feature was added upon request, if you read the comment’s then you’ll know who requested it. Here is an example of the function being used
echo getTopRated(10,'articles','article_id','article_title');
What this is doing getting the top 10 rated articles. You must specify how many top rated items you want to return, fallowed by what table name you are looking in, followed by the id in the table (auto incremented, primary key) and the title/name you want to display.
The function will return the following:
- Baby Born (5.0)
- NY loses to BC (3.4)
- Man loves food (3.2)
- Nike to sponsor vegetables (1.5)
This is returning the article_title along with the rating for it.
Additional License Info – Creative Commons
http://creativecommons.org/licenses/by-nc-nd/2.5/ca/


is it required to download the script again?
as for toprated function, i just store the ratings itself in a database with rating_id rating_num etc cos i simply use php includes for my website
the way the toprate function is now it wont work for me, do you know how i would make it to work for me?
also top rated would have a title, is there a way how i could store a title within the
echo pullRating(35,false,false,false,NULL); ???
The title should be stored in your database. When you are using pullRating to call the id 35, you can then use the getTopRated to display the "title" field. Like this:
The rating_id in the ratings table should be your article_id from the articles table or whatever your primary key is.
if i make that nothing is displayed because my ratings dont have a title, just id, rating_id, rating_num, so it dont belong to anything else
i guess i need to recode the function for toprated somehow, but i got no clue :P
also spiders are rating my videos, what would i need to put in the robots.txt ?
disallow: includes/rating_process ??
i made a field in sql after rating_id named rating_title and added a title manually for testing
then i used this to call it, but it simply dont display
echo getTopRated(10,'ratings','rating_id','rating_title'); ?>
in my pages the rating id is named like afro01
so from the above iam calling the table ratings, and the fields id and title, so why dont it display something?
It seems like the hover-over star images do not line up correctly with the normal star images. It also seems to affect the 1st star more than the other ones -- it gets gradually better towards the 5th star. What causes this and how can I fix it? Thanks.
I have copied the files and directories into the same directory as the test page on my local server.
I have set up a database "ratings" & table using the sql query you provided in myadmin.
here is a copy of my test page.
test.php
What am I missing in setting this up to work ?
Pleae explain in layman terms because I am just learning.
Thanks Jeff
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ENGINE=MyISAM DEFAULT CHARSET=latin1' at line 7
On my header tpl file, I place
on my view video section i have,
But nothing comes up.
Any idea why it's not working?
Thanks.
thnxxx for ur scripts ,its wprking so good
but i have some problem in the Top 10 votes
i have a table named “gallery_fotos” contains gallery_fotos_id,gallery_fotos_name
this is my code
do{?> <img src="../mystique/Admin/gallery/" /> }while($row_Recordset1 = mysql_fetch_assoc($Recordset1))?> Top 10 Votesdo i suppose to put the rating _id in this table???
please tell me what is wrong?
Theres just one thing missing: a guide how to use different sized stars for the rater.
I suppose i have to change some values in rating_style.css and in rating_update.js.
Could you help me here please.
Sincerly,
gorgon
I agree with Gorgon, the ability to resize the display would be awesome. I would love to use this in a very minimal form.
As such, the ability to not display the rating progress bar and the 'thanks for voting' message would also be excellent.
Ta for sharing!
@Jeff: To not display that you can just remove or comment out the lines:
in the javascript
the star rating looks great.
unfortunatly its not updating the database with the new rate,
it gives the rating progress bar that does not progress and thats it.
do you have any idea whats wrong?
I can see the rates if I insert directly to the database, but not through the script....
please help.
Now i am using it on my website to rate movies!
how to fix em?
ive problems with your ajax script!
if somebody votes, the "thank you" message appears!
But theres n error!
Message about the stars: Rated: NaN/5 (1 Vote)
Ive looked up the data in my databse! There are 0 lines! Ive i reload the page: 0 Votes!!
What should I do?
Dennis
ive downloaded your script again!
uploaded it to my server (after edit config!)
so i get errors:
some pathes are wrong! ive checked this!
youve done some little mistakes i think:
include(includes/rating_config.php) rating_functions.php on line 2 (no such file)
ive changed this to: include(rating_config.php)
upload it again!
no errors anymore!
But same problem as i write above!
I could vote! But date doesnt went into my database!
Could it be an error, because my username an my databse has the same names?
Or what shoul i do?
dennis
silly
i mean: But data doesnt went into databse!!!
dennis
my robots:
User-agent: *
Disallow: /includes/rating_process.php
Disallow: /includes/rating_functions.php
Disallow: /includes/rating_config.php
Disallow: /js/rating_update.js
may that be because i have in htaccess: php_value include_path .:/home/xxx/public_html/
this way i have 2 slahes, could that be the problem? if not i need your help urgent, thanks
NOT THE DB PROBLEM... FOR ANYONE WHO HAS THIS PROBLEM TRY UPLOADING DIRECTLY THAN VIA FTP
THANX AWFULLY,
JORDAN,ITS BEYOND WORDS
I have copied the files and directories into the same directory as the test page on my local server.
I have set up a database “ratings” & table using the sql query you provided in myadmin.
What am I missing in setting this up to work ?
Pleae explain in layman terms because I am just learning.
Thanks Jeff
@Satish: I can't even attempt to help you if you don't provide any sort of error message.
For those, going to use this script for multiple Voting on the e-page, it seems for me to be more efficient, to create a separate table in the database for storing the total number of votes and average grade and not to calculate them every time for each user downloading the e-page.
Also noticed, that changing the image with stars make problems for IE6 showing background
--> just do in CSS: background-position: 0px -10px;
worked fine for me.
Hey I got it working and pulling info like I need it to. I have 2 questions:
1). Could another variable be added to the getTopRated function call? If so how? I tried adding it to the function and the function call but it's not being translated in the process.
On Ratings Function I added this:
function getTopRated($limit, $table, $idfield, $namefield, $songname)
On the function call file I did this:
The limit, songlist, id and artist work fine but I get nothing with the title. I'm assuming the $songname part is not being processed.
2). I'm using your script (wonderful by the way), to rate songs being played on my internet radio station and it works great after getting a better understanding and with a minor tweak. Is there a way to include time into this, say like the top 20 last 4 weeks, or in the past week?
Wonderful rating script i must confess,Please i need to know how i can deal with a situation where i want to modify the rating_process.php file in order to have a userid variable integrated into the mysql insert statements on line 50 and 92.
What i actually what to achieve it to be able to display the individual rating given a particular registered user.
i have already created an adition field in the ratings table called userid but when i tried to modify the script by defining the userid variable using the users session variable established while logging in, it doesn't seem to insert the userid field.
Also please how can i get to display just the particular rating associated with a specific user.
Can I get a exemple of this script for J2EE(struts for exemple)?
Thank You
@brown: Good luck! ;)
This is really a great stuff. The images are getting overlapped. Any idea why? You can check it here : http://htmlemailers.com/test.php
Suggestions very much appreciated.
Thank you.
regards
Carboncy
But I have 2 questions :
1- What exactly I have to include in the rating_functions.php file at line 127 if I want to add a message like: You've already voted" ?
2- Is it possible that you explain how to do to make the top rated articles working ? I've found a solution in the comments on Magusa's site but I can't adapt it here...
Script is running smoothly but 1 little bug i have found.
in the top 10
- if 20 items rated 5/5, the top 10 shows them but not in right order
- it should sort them by rating ofc, but also number of votes
like i have 10 items rated 5/5 1 time vote
a few others are rated 5/5 as well but got 3-4 votes, so they should stand in top 10 at the top, but they arent even in top 10.
i hope you know what i mean, and a quick fix would really be helpful, thanks
Great script. Installed it, modified it slightly (our rating_id's are alpha-numeric... all I did was change the structure of the DB to varchar) and it works flawlessly.
The big problem is SPAM entries. I'm seeing lots of sudden entries with IP's from Russia and all over the place with the same star rating (like 20 entries in a row with a star rating of say 2). Our site is pretty much US based, so I'm sure these are random votes. Any ideas on how to stop that? The rating system is pretty worthless with these random votes. Anyone else experiencing this? I realize a Captcha would kill the Ajax effect.
@Sam: I will try to figure out a work around for the spamming ratings... I am already checking IP and cookies, I'm not sure what else to do to prevent itl. Anyone have any ideas?
In what file your corrected the order?
i cant simply replace everything because i have made changes to the script in order to work for me :(
this code i currently use, ripped a few parts out
[code]
function getTopRated($limit){
$result = '';
$sql = "SELECT rating_id as thenamefield,ROUND(AVG(rating_num),2) as rating
FROM ratings GROUP BY rating_id
ORDER BY rating DESC LIMIT ".$limit."";
$sel = mysql_query($sql);
$result .= ''."\n";
while($data = @mysql_fetch_assoc($sel)){
$result .= '» '.$data['thenamefield'].' ('.$data['rating'].')'."\n";
}
$result .= ''."\n";
{
$result = str_replace("_"," ",$result);
}
return $result;
}
[/code]
i tried several things with the updated code but i dont get it to work
If I add the rating to a page that uses SEO friendly links it wont work, but it will work on normal pages for example
www.mysite.com/rating.php work fine BUT
www.mysite.com/My-Link/Rating/ wont work, however they are exactly the same page only the second page uses mod rewrite htaccess file to create the SEO page link.
do you have any suggestions to get this working on these types of page.
any help would be much appriciated
regards
wayne
So your query would look something like...