Ajax Star Rating
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
- Uses AJAX Post (more secure than GET)
- Non-obtrusive (works with javascript disabled)
- Does not allow multiple votes - checks against IP
- 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:
$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.
`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.
Now to call the rating stars to display on your page, simply add:
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
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/
50 Sexy Responses to Ajax Star Rating
hey, cool new look ![]()
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); ???
@sebastian: Yes you need to download the script again, but you only need to replace the “ratings_process.php” file.
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:
getTopRated(10,'articles','article_id','article_title');
The rating_id in the ratings table should be your article_id from the articles table or whatever your primary key is.
hmm i allready tried that, but i dont store website info in database, only the rating itself
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
also spiders are rating my videos, what would i need to put in the robots.txt ?
disallow: includes/rating_process ??
@sebastian: I suggest making a field to store the title WITH the id. The whole purpose of this is that it’s dynamic. To disallow bots it would be something like
User-agent: *
Disallow: /pathto/includes/rating_process.php
ok the disallow is working, the top items doesnt
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?
@sebastian: You are using getTopRated in the wrong way. You shouldn’t be grabbing from the ratings table, it knows to look for the ratings table. You need to supply the table name of the item you are rating, the foreign key OF the rating_id and the field you want to display in the HTML, which is player_name in example below. This has nothing to do with the ratings table. Example getTopRated(10,’players’,'player_id’,'player_name’). Now player id is stored as rating_id in the ratings table, it just making the co-relation between the two so it can gather the correct data. If you are still have troubles please email me instead.
Hi, I’ve set up this script but I’m having a problem with the stars moving slightly when hovered over. I’ve noticed that the same problem occurs at http://www.rockmodelagency.com/Pinkdc
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.
@Greg: My feeling would be that the CSS was modified. If you notice in my demo, the stars don’t do that.
all i get is a blank page ?
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
When I try and create the MySQL database I get the following error:
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
@Tim: Try removing “DEFAULT CHARSET=latin1″ then running the query.
Hi, I love you ajax rating. I can’t seem to get it to work on my page. I’m using clipshare and the file that it’s pulling from is a tpl and a php file.
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.
hii Jordan Boesch
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 Votes
do i suppose to put the rating _id in this table???
please tell me what is wrong?
@ausgezeichnete: I don’t fully understand the problem you are having.
Hey, i love this star rater! Its easy to use and to implement.
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
Excellent rating system, I love the way it works.
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!
@gorgon: You will have to do the math in the CSS file. Whatever size you enhance the stars by in Photoshop, do the same in the CSS file - of course it will involve a little division to get the exact with of each star. ‘;
@Jeff: To not display that you can just remove or comment out the lines:
loader.innerHTML = '
‘; and loader.innerHTML = ‘
in the javascript
Hi,
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.
Thx, it’s not been that difficult to alter the rater a little bit.
Now i am using it on my website to rate movies!
i am getting a nan/5 when these things are clicked
how to fix em?
@Avin: You need to make sure you’re actually connecting to the database and that your files have the proper paths.
hi jordan!
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
@dennis: If they aren’t going into the database, your database connection info is wrong or you have the path’s to the files mixed up.
ok, ive checked the config file! my databse setting are right (checked: 12 times!!!)
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
ive written: But date doesnt went into databse!
silly
i mean: But data doesnt went into databse!!!
dennis
hi jordan as you know i use it on anachrony, tho there are still heavy problems with search engines and i have no clue why.i have put every file into robots.txt tho search engines still vote cos they see the rating stars as links…they alsways vote 1
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
GOT IT RIGHT
NOT THE DB PROBLEM… FOR ANYONE WHO HAS THIS PROBLEM TRY UPLOADING DIRECTLY THAN VIA FTP
THANX AWFULLY,
JORDAN,ITS BEYOND WORDS
Is it possible to use this script using TXT database ?
@Saud: If you can figured out a way, sure. But it does not use .txt databases, it uses MySQL only.
all i get is a blank page ?
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
@Webmaster: You would have to edit the rating_functions.php file on line 127. Include your message in the return statement.
@Satish: I can’t even attempt to help you if you don’t provide any sort of error message.
Hello Jordan, this is realy good example, how it could be done with AJAX..
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.
@sebastian: Yes you need to download the script again, but you only need to replace the “ratings_process.php” file.
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:
getTopRated(10,'articles','article_id','article_title');
The rating_id in the ratings table should be your article_id from the articles table or whatever your primary key is.
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?
Hello Jordan,
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.
Hi all,
Can I get a exemple of this script for J2EE(struts for exemple)?
Thank You
@tunde aguda: You will have to pass in a $_SESSION['user_id'] into the function (if you’re using sessions).
@brown: Good luck! ![]()
Hi,
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
Hi Jordan, congratulations for your script. It works really great ! Thank you ! It’s exactly what I am searching for.
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…
@Luc: You could just make line 127 say
‘. The description of the top rated is above.
Hey, got it all worked out and it rocks! Now my listeners can rate songs when they request them or when they are logged into their Control Panel. Thanks!
hi Jordan,
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
Hi Jordan,
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.
@Sebastian: I will fix this in the next version.
@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?
hey jordan, thx for the update.
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 ![]()
okay i forgot to post ![]()
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
Hi jordan nice script but unfortunately it wont work on my site (well it does but will explain)
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
http://www.mysite.com/rating.php work fine BUT
http://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
@Sebastian: I re-wrote some parts of the SQL query on line 182 in rating_functions.php. I added SELECT COUNT(ratings.id) as rates and ORDER BY rates DESC, rating DESC
So your query would look something like…
$sql = "SELECT COUNT(ratings.id) as rates,rating_id as thenamefield,ROUND(AVG(rating_num),2) as rating
FROM ratings GROUP BY rating_id
ORDER BY rates DESC,rating DESC LIMIT ".$limit."";
@Wayne: I would really have to see the contents of the page as to why it’s not working. If you’re typing in Rating and you have mod rewrite telling this to render as rating.php, I don’t see why it won’t work.
[...] all of the features I was looking for. The best rating system I found was written byJordan Boesch, AJAX star rating. This AJAX script is now fully implemented on all of ShortcutGuide. Sorting by ratings will be [...]




had this to say...
Update: I have updated this to fix the sanitizing before the $_POST and $_GET vars get put into the SQL query. Sorry about everyone’s comments getting removed. I don’t have time to re-insert all 200 of them :/