jQuery Tutorial : Simple ajax star rating with php

by ronggur on May 30, 2009

I made this simple ajax star rating for my latest poject. And now i want to share it to you. Let’s start it :D .

Step 1 : CSS Star Rater

First thing is the star rater. I got this cool ‘css star rater’ from http://www.komodomedia.com/ . I assumed that we already understood how to use it, so we will not talk too much about this ‘css star rater’.

Step 2 : Create MySQL table

Next is create table (using MySQL) to store the data. You can copy the script below


CREATE TABLE IF NOT EXISTS `vote` (
`counter` int(8) NOT NULL default '0',
`value` int(8) NOT NULL default '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Step 3 : PHP

After finished create table, then we can start create some php code to handle input, update and retrieve data from the database, here is the code. I added some important comment in it


<?php

// connect to database
$dbh=mysql_connect ("localhost", "username", "password") or die ('Cant connect to the database');
mysql_select_db ("rating",$dbh);

if($_GET['do']=='rate'){
// do rate
rate();
}else if($_GET['do']=='getrate'){
// get rating
getRating();
}

// function to retrieve
function getRating(){
$sql= "select * from vote";
$result=@mysql_query($sql);
$rs=@mysql_fetch_array($result);
// set width of star
$rating = (@round($rs[value] / $rs[counter],1)) * 20;
echo $rating;
}

// function to insert rating
function rate(){
$text = strip_tags($_GET['rating']);
$update = "update vote set counter = counter + 1, value = value + ".$_GET['rating']."";

$result = @mysql_query($update);
if(@mysql_affected_rows() == 0){
$insert = "insert into vote (counter,value) values ('1','".$_GET['rating']."')";
$result = @mysql_query($insert);
}
}

?>

Step 4 : JavaScript

Next thing is javascript code. Below is the code, you can put this code between <head> tag or put it in separated javascript file.


<script type="text/javascript">
$(document).ready(function() {
// get current rating
getRating();
// get rating function
function getRating(){
$.ajax({
type: "GET",
url: "update.php",
data: "do=getrate",
cache: false,
async: false,
success: function(result) {
// apply star rating to element
$("#current-rating").css({ width: "" + result + "%" });
},
error: function(result) {
alert("some error occured, please try again later");
}
});
}

// link handler
$('#ratelinks li a').click(function(){
$.ajax({
type: "GET",
url: "update.php",
data: "rating="+$(this).text()+"&amp;amp;do=rate",
cache: false,
async: false,
success: function(result) {
// remove #ratelinks element to prevent another rate
$("#ratelinks").remove();
// get rating after click
getRating();
},
error: function(result) {
alert("some error occured, please try again later");
}
});
});
});
</script>

Don’t forget to link the jquery library into your document


<script src="rating/jquery.min.js" type="text/javascript"></script>

Step 5 : Put it all together

Put your css, javascript in one html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>jQuery Tutorial : Simple ajax star rating</title>
<meta name="Keywords" content="Star rating, jQuery, ajax">
<meta name="Description" content="jQuery Tutorial : Simple ajax star rating">
<meta http-equiv="Content-Language" content="en">
<meta name="robots" content="index,follow">
<style>
body{
font:12px Arial, Helvetica, sans-serif;
padding:40px;
}
</style>
<script src="rating/jquery.min.js" type="text/javascript"></script>
<script src="rating/starrating.js" type="text/javascript"></script>
<link href="rating/starrating.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<h2>Star Rater</h2>
<ul class='star-rating'>
<li class="current-rating" id="current-rating"><!-- will show current rating --></li>
<span id="ratelinks">
<li><a href="javascript:void(0)" title="1 star out of 5" class="one-star">1</a></li>
<li><a href="javascript:void(0)" title="2 stars out of 5" class="two-stars">2</a></li>
<li><a href="javascript:void(0)" title="3 stars out of 5" class="three-stars">3</a></li>
<li><a href="javascript:void(0)" title="4 stars out of 5" class="four-stars">4</a></li>
<li><a href="javascript:void(0)" title="5 stars out of 5" class="five-stars">5</a></li>
</span>
</ul>
</body>
</html>

That’s it! :D . You can add some modification like notification, or loader while processing.

- View Demo

- Download zip file jQuery Tutorial : Simple ajax star rating with php (5817)

This article inspired by http://www.yvoschaap.com/

You can give me some coffee if you want to :D

  • Pingback: jQuery Tutorial : Simple ajax star rating with php | Ronggur …

  • Pingback: jQuery Tutorial : Simple ajax star rating with php | pc-aras

  • http://www.urban-butterfly.co.uk Tom

    Excellent tutorial, thank you – however, how would I go about expanding this example for use over several pages of a site, with each page having its own rating?

  • http:ronggur.com ronggur

    Thank’s Tom for your comment.

    However when you want to put in other page, you just have to add the ‘page id’ in your php function ( getRating() and rate() ) and also in javascript.

    In javascript file, you can change these lines

    [line 10] data: “do=getrate”
    [line 28] data: “rating=”+$(this).text()+”&do=rate”

    into something like this

    [line 10] data: “pageID=”+< ?php$_GET['pageID']?>+”&do=getrate”
    [line 28] data: “rating=”+$(this).text()+”&pageID=”+< ?php$_GET['pageID']?>+”&do=rate”

    don’t forget to add pageID into your sql.

    Thank you

  • http://www.urban-butterfly.co.uk Tom

    Thank you kindly, I’ll be sure to give this a go and return with my feedback.

    Kind regards.

  • http://none tom B

    Hello i love the code and i have been playing with it to try and accept the ratings over separate pages with little joy. I have got it to insert an id from a session called user into the database and only show to results matching the id but i can not get it to vote separately on different id’s they all count on the first one i vote for. I read the reply about changing the javascript on lines 10 and 28 but i could not make the adjustments to make it call the vaule of the session user and us that as an id so i can then make multiply votes.

    Can you help i am good with php but not with javascript or Ajax i am currently learning..

    id is set by a session called user…

  • http:ronggur.com ronggur

    How about by calling php script (the session user id) within the js file?
    Btw, you also can call the url for processing the vote like example below, without setting the “data” option

    ex :
    url: “/Album/RatePhoto/” +

    user session

    ,

  • http://none tom B

    Like i said i am new to JavaScript and when you say call the the php session into the JavaScript file is this done the normal way example:

    add into the starrating.js

    How would i add it into the JavaScript file i know its a pain but i have been trying to learn this with little joy as i need to learn the code more.

    I need to know the easiest way to adjust this this to accept the session value this what i have done so far

    below is the update.php minus the server details:

    The JavaScript file i have not touched as i can not get anything to work with my knowledge of JavaScript. I know your busy but any chance of helping me out. The update php works fine with my adjustments makes it so if i add entries to the database myself then the stars display correctly for different users profiles just the rating part that does not work..

    HELPPPP

  • http:ronggur.com ronggur

    hi tom, i sent you email

  • http://www.urban-butterfly.co.uk Tom

    Hi Ronggur, original poster here. I haven’t had an opportunity to try what you suggested yet, but as I see another poster has had difficulty with your suggestion, would you be able to e-mail me too?

    Kind regards – I’m sure I’ll be able to sort you out a donation for your trouble too :-)

  • http:ronggur.com ronggur

    Hi,

    Sorry i thought you already solve it.
    Actually you can put “the handler link” method into your php document (this is what i did in my project), so you can keep call your php variable.
    Or you can store your iduser in a cookie and then use jquery cookie plugin to call it, but i have not try it yet.

  • http://www.urban-butterfly.co.uk Tom

    Thanks for the speedy reply Ronggur. I’m not planning on implementing this to my site for a little while yet, so perhaps if you get it working and maybe make a new post? I’ve seen loads of these examples, and yours was the best, but none for multiple ratings/pages – and I know there’s a lot of people who want this.

    Unfortunately, I currently lack the time and PHP knowledge to sit down and figure it out myself :-(

    Kind regards.

  • http:ronggur.com ronggur

    Your welcome, maybe oneday i’ll post it, that’s a good idea :D .
    Actually many things i want to share in my blog :D , i just can’t get enough time to make it as a full post.
    These whole works is gettin me crazzy.. ahehehue..

    cheers

  • ryan

    thanks a lot for this script. most i came across were far too bloated. this one is simple and easy to customize. i was able to get it up and running with a pre-existing database in less than an hour.

  • http:ronggur.com ronggur

    thanks for coming ryan. glad to know this article work for you

  • http://embaba.net ahmed

    hii

    i use this code but their one problem as i make it us id for each file but the link in 8 has some diff data i don’t know the reason of it

    url: “fun.php”,
    data: “fun=star&do=getrate&id=”+fid,

    the url that generate is like that

    http://localhost/gametube/fun.php?_=1259822303255&fun=star&do=getrate&id=338

    i didn’t need it like that it should be
    http://localhost/gametube/fun.php&fun=star&do=getrate&id=338

  • http:ronggur.com ronggur

    are you implement it in a opensource cms or framework? those url maybe automatically generated by your cms or framework.. maybe

  • Chritchan

    Hello man,
    It’s a nice code, verry clear but i’m not able to modify your work for my own use.

    In a few word, I would like to use your code to make this kind of page : http://www.logoheroes.net/logos/colorful

    How is it possible to apply a vote to an itemID.
    Select the item out of the database with the vote results…

    I’m in front of a big wall :D Can you help a belgian webdesigner ? ^o^

    Thx alot man !

  • Pingback: jQuery Tutorial : Simple ajax star rating with php | MySandbox

  • http:ronggur.com ronggur

    @Chritchan : hi chritchan, i have new post about what you need (maybe) hehe.. check it out http://sandbox.ronggur.com/2010/01/19/jquery-tutorial-simple-ajax-star-rating-with-php-extended/

  • asiri

    In javascript file, you can change these lines

    [line 10] data: “do=getrate”
    [line 28] data: “rating=”+$(this).text()+”&do=rate”

    into something like this

    [line 10] data: “pageID=”++”&do=getrate”
    [line 28] data: “rating=”+$(this).text()+”&pageID=”++”&do=rate”

    can you tell me the php part also

  • http://www.just4freaks.de Markus

    thanks mate
    i used this tutorial in one of my Typo3 Extensions
    it works perfect

  • http://kh3.us Gregory Despain

    Hello you cos I love this site, I would enjoy if you would want me to write a adorable review about your fine wordpress blog in my small would you allow me to? Webmaster Community

  • http:ronggur.com ronggur

    @Gregory : are you sure? i never have a chance to update this blog lately hehehe.. But that would be great if want to write a review about my blog. I really appreciate it.. thanks!

  • Pingback: 4 x 5 Star Rating Tutorial With jQuery In The Hot Seat « jQuery Fun - Having fun & making plugins

  • http://www.prepaid-mobile.ch/ prepaid vergleich

    I created a new typo3 site and I don’t have a good design yet. But I hope your tutorial will help me a bit, but it looks complicated for a beginner like me.

  • Marchel

    Hi… I found your tutorial really interesting.. I am stuck with this rating stars system :( I coded a php for rating but it using radio button and my boss want it in jquery or ajax…
    Can u help me ?
    I tried to modify your script but i am not really good with the ajax.. i don’t know how to get the value… I added a news_id so that every article can be rated.. how to get the news_id if i combine it with your script ?

  • http://fakeheal.web-tourist.net Fakeheal

    My rating system does not work! It doesn’t make records. How can I fix it? I changed in update.php host,database, user, password and created a database. What else should I do?

  • http:ronggur.com ronggur

    Probably your ajax/javascript does not work correctly?

  • http://fakeheal.web-tourist.net Fakeheal

    Wow, u r fast. :) )

    Well I just downloaded the archive u’ve given and made changes in update.php.

    (and imported the SQL file in my database)

  • http://www.webjam.com/topairlines/~Media?id=96690b2b-5bba-464c-83a8-60acdb87e7fb airline information

    On December terrorists simultaneously attacked El Al ticket counters at the Rome Italy and Vienna Austria airports using machine guns and hand, airline flight tracking, 9110, airlines myrtle beach sc, %), here, 8-[, here, >:D, airline history, mzz, link, %(, airlines 5 star, 2584, air lines europe, 49100, airline ticket search, ahz, airline net, =-(((, airlines 3, 959, cheap airline seats, ryjl, airline tickets london, 7095, airlines dogs, xtg, airlines companies, 8-[, united airlines phone number, aqh, japan airlines 123, ydprmr, airlines questions, 55646, discount airline tickets flights, >:]], airline ticket information, acdh, airlines tickets online, =-), here, %-[[, here, 8), airlines reservations, dzbcs, airline 2, %((, airlines lufthansa, 714, air line ticket, 076, online travel agent, 522, airline safety, =))),

  • oracons

    Hi everyone & @Ronggur, I´m using dreamweavercs5, php, mysql, javascript & css to develop a physician’s directory (all the physicians store in the database’s table) if user find physician & want to and rate to the particular physician (the page show multiple physicians). I need to rate physicians using your 5 star rating system. I saw many different plugins that rate pages and posts. But, besides posts and pages, what I need is to rate several database records (physicians) in the same post/page. I have a list of links, where users cane rate each one of them. Any ideas? Thanks!

  • http://www.hackitz.ca/ HackitZ

    Hi ronggur,

    I must say this was the easiest script i could find and it just works, no fuss no muss. Kudo to you for the great guide.

    I have a question for you, how hard would it be to add a text field to show total and average votes?

    Thanks again.

  • http://www.hackitz.ca/ HackitZ

    Hi again, ok as this is simple and silly i still need to ask, as mentioned the script works and works well.

    I just tried to add the html info to another page and it pulls the same data from the original page. how can i install this on multiple pages?
    I’m using the stars to rate pictures and each page has it’s own picture, you can see it here
    pictures

  • http://sandbox.ronggur.com ronggur

    Hi Hackitz,

    Actually I wrote another article about this star rating, you can fin out here http://sandbox.ronggur.com/2010/01/19/jquery-tutorial-simple-ajax-star-rating-with-php-extended/. This article is almost the same, but i add ‘id’ as unique id for each star rating.. maybe you’ll need to modify it a bit..

    Thanks for coming

  • http://sandbox.ronggur.com ronggur

    Hi Oracons, I think this article http://sandbox.ronggur.com/2010/01/19/jquery-tutorial-simple-ajax-star-rating-with-php-extended/ will help you (I hope so) :D .. Ofcourse you’ll need to modify it

  • http://www.netherlandstraveladvisor.com Holley Mcwalters

    Thank you for giving us some honest information on this topic. I have located a wide variety of good ideas about travel tips and some poor ideas. Do you have any more honest ideas or places on the Internet that I can find more detailed suggestions? This would be quite appreciated! Either way, continue the good work!

  • NIGHT

    Hi Ronggur,
    I like you work and it’s very helpful, but can you help me making a star rating for each picture that shown on a java window like this: http://www.lokeshdhakar.com/projects/lightbox2/#example
    I just want to make the code for each picture.
    I hope you understand and sorry for my english..
    Please reply fastly :)

  • Mark

    Hi

    I love the look of the rating system, any ideas how I can expand this over say 5 questions as a feedback system.

  • ronggur
  • Anonymous

    gue pake buad okecoy tipi yak.. :D

  • Dexterous

    Hi, 

    very good and usefule tutorial 

    But I can see on demo page If I am giving rating then value is sent to other page but why that rating is not selected? why all stars become blank again ?

    Waiting for your reply on this.

    Thanks & Regards
    Dexterous

  • http://sandbox.ronggur.com Ronggur

    Hi Dex, thanks for coming. Please visit this post http://sandbox.ronggur.com/2010/01/19/jquery-tutorial-simple-ajax-star-rating-with-php-extended/ for more advance sample, the demo still working.

    I curently don’ have a chance to check demo from this post. Or maybe you can download the zip file and test it in your local computer. And let me know if it is still not working on your computer.

    Thanks

  • http://www.hamed-bd.com Hamed

    thanks for your clean and brief code!

  • http://twitter.com/chowdaryorkut Chowdary orkut

    i want to add multiple page for different   rating like game rating give me the suggistion

  • http://sandbox.ronggur.com Ronggur