jQuery Tutorial : Simple ajax star rating with php

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 (1532)

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

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

  • Share/Bookmark

{21} Responses to “jQuery Tutorial : Simple ajax star rating with php”

  1. [...] more: jQuery Tutorial : Simple ajax star rating with php | Ronggur … Share and [...]

  2. [...] article inspired of http://www.yvoschaap.com/ source :: ronggur Share and [...]

  3. 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?

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

  5. Tom

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

    Kind regards.

  6. 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…

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

    ,

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

  9. ronggur

    hi tom, i sent you email

  10. 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 :-)

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

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

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

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

  15. ronggur

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

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

  17. ronggur

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

  18. 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 !

  19. [...] people ask me question about how to implement my last star rating in multiple star rating, and here is the answer on how to implement [...]

  20. 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/

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

Leave a Reply