Internet Explorer 6 is why I stab people. -AJ Cates
Submit your own quote
  • home
  • about
  • lab
  • work
  • contact

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

Download it! (v1.7)

Try the demo!

 

star rating example

 

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:

 

PLAIN TEXT
PHP:
$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.

 

PLAIN TEXT
SQL:
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.

 

PLAIN TEXT
PHP:
include("includes/rating_functions.php");

 

PLAIN TEXT
HTML:
<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:

 

PLAIN TEXT
PHP:
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

 

PLAIN TEXT
PHP:
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/

Posted February 18, 2008

49 Sexy Responses to Ajax Star Rating

Jordan Boesch
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 :/

February 24, 2008 at 9:53 am
sebastian
had this to say...

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); ???

February 24, 2008 at 10:25 am
Jordan Boesch
had this to say...

@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.

February 24, 2008 at 10:45 am
sebastian
had this to say...

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 :P

also spiders are rating my videos, what would i need to put in the robots.txt ?
disallow: includes/rating_process ??

February 24, 2008 at 11:38 am
Jordan Boesch
had this to say...

@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

February 24, 2008 at 1:03 pm
sebastian
had this to say...

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?

February 24, 2008 at 2:10 pm
Jordan Boesch
had this to say...

@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.

February 24, 2008 at 3:22 pm
Greg
had this to say...

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.

February 25, 2008 at 1:53 am
Jordan Boesch
had this to say...

@Greg: My feeling would be that the CSS was modified. If you notice in my demo, the stars don’t do that.

February 25, 2008 at 7:09 am
Jeff
had this to say...

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

March 4, 2008 at 4:55 pm
Tim
had this to say...

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

March 9, 2008 at 6:15 pm
Jordan Boesch
had this to say...

@Tim: Try removing “DEFAULT CHARSET=latin1″ then running the query.

March 9, 2008 at 6:18 pm
William
had this to say...

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.

March 11, 2008 at 7:11 pm
ausgezeichnete
had this to say...

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?

March 14, 2008 at 3:54 pm
Jordan Boesch
had this to say...

@ausgezeichnete: I don’t fully understand the problem you are having.

March 16, 2008 at 7:02 pm
gorgon
had this to say...

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

March 17, 2008 at 1:20 pm
Jeff
had this to say...

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!

March 18, 2008 at 7:10 pm
Jordan Boesch
had this to say...

@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 = 'loading‘; and loader.innerHTML = ‘

Thanks for voting!

‘;

in the javascript

March 18, 2008 at 8:12 pm
Renata
had this to say...

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.

March 19, 2008 at 10:19 am
gorgon
had this to say...

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!

March 21, 2008 at 11:40 am
Avin
had this to say...

i am getting a nan/5 when these things are clicked
how to fix em?

March 23, 2008 at 8:00 am
Jordan Boesch
had this to say...

@Avin: You need to make sure you’re actually connecting to the database and that your files have the proper paths.

March 23, 2008 at 8:46 am
dennis
had this to say...

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

March 25, 2008 at 4:58 am
Jordan Boesch
had this to say...

@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.

March 25, 2008 at 6:21 am
dennis
had this to say...

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

March 25, 2008 at 6:35 am
dennis
had this to say...

ive written: But date doesnt went into databse!
silly
i mean: But data doesnt went into databse!!!
dennis

March 25, 2008 at 6:38 am
sebastian
had this to say...

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

March 30, 2008 at 4:04 pm
Avin
had this to say...

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

April 1, 2008 at 10:00 am
Saud
had this to say...

Is it possible to use this script using TXT database ?

April 3, 2008 at 3:42 pm
Jordan Boesch
had this to say...

@Saud: If you can figured out a way, sure. But it does not use .txt databases, it uses MySQL only.

April 3, 2008 at 4:57 pm
Satish
had this to say...

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

April 9, 2008 at 2:56 am
Jordan Boesch
had this to say...

@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.

April 9, 2008 at 12:20 pm
Alex
had this to say...

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.

April 14, 2008 at 6:10 pm
NiaRadioNetwork
had this to say...

@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?

April 17, 2008 at 3:29 pm
tunde aguda
had this to say...

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.

April 18, 2008 at 7:54 am
brown
had this to say...

Hi all,
Can I get a exemple of this script for J2EE(struts for exemple)?
Thank You

April 18, 2008 at 7:45 pm
Jordan Boesch
had this to say...

@tunde aguda: You will have to pass in a $_SESSION['user_id'] into the function (if you’re using sessions).
@brown: Good luck! ;)

April 18, 2008 at 7:49 pm
Carboncy
had this to say...

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

April 19, 2008 at 5:38 pm
Luc
had this to say...

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…

April 20, 2008 at 9:18 pm
Jordan Boesch
had this to say...

@Luc: You could just make line 127 say

You already voted

‘. The description of the top rated is above.

April 20, 2008 at 9:56 pm
NiaRadioNetwork
had this to say...

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!

April 21, 2008 at 2:57 pm
Sebastian
had this to say...

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

May 4, 2008 at 8:02 am
Sam
had this to say...

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.

May 6, 2008 at 7:56 pm
Jordan Boesch
had this to say...

@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?

May 11, 2008 at 6:02 pm
Sebastian
had this to say...

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 :(

May 21, 2008 at 7:17 am
Sebastian
had this to say...

okay i forgot to post :P
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

May 21, 2008 at 8:05 am
Wayne
had this to say...

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

May 21, 2008 at 8:27 am
Jordan Boesch
had this to say...

@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."";

May 21, 2008 at 5:56 pm
Jordan Boesch
had this to say...

@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.

May 21, 2008 at 5:59 pm

Sorry, comments closed

Recent lab work

  • Database CSV Class
  • imageTick for jQuery
  • wiggleSlide for jQuery
  • CSV 2 PHP 2 MySQL Insert
  • jTabber for jQuery
  • Ajax Star Rating
  • Tiny Form Class

Things I like

  • cakephp
    CakePHP Rapidly develop robust web applications
  • jquery
    jQuery Traversing the DOM just got a lot simpler
  • asparagus
    Asparagus Even more nutritious than programming
© boedesign.com 2008 - God bless Wordpress