Warning: ob_start(): non-static method wpGoogleAnalytics::get_links() should not be called statically in /home/ronggur/public_html/sandbox/wp-content/plugins/wp-google-analytics/wp-google-analytics.php on line 259
jQuery Tutorial : Simple ajax star rating with php | MySandbox

jQuery Tutorial : Simple ajax star rating with php (extended)

by ronggur on January 19, 2010

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

1. Upgrade latest table

Since you’ll need to add ‘id’ on multiple record then we need to upgrade the existing table. Here is the full sql

CREATE TABLE IF NOT EXISTS `vote` (
 `id` int(11) NOT NULL auto_increment,
 `desc` varchar(50) NOT NULL,
 `counter` int(8) NOT NULL default '0',
 `value` int(8) NOT NULL default '0',
 PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `vote`
--

INSERT INTO `vote` (`id`, `desc`, `counter`, `value`) VALUES
(1, 'star - 1', 0, 0),
(2, 'star - 2', 0,0);

2. CSS

We still can stylesheet from the previous post. No need to modify it.

3. PHP files (index.php & update.php)

There are some code changes in this files. If in previous post we just need an html file to represent the star rating, now we need php file to do it. Here is full code for index.php and some simple code explanation in it

<!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">
<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>
<?php
// include update.php
include_once 'update.php';
// get all data from tabel
$arr_star = fetchStar();
?>
<?php
// start looping datas
foreach($arr_star as $star){ ?>
<h2>Star Rater - <?php echo $star['id'];?></h2>
<ul class='star-rating' id="star-rating-<?php echo $star['id'];?>">
<?php /* getRating($id) is to generate current rating */?>
 <li id="current-rating-<?php echo $star['id'];?>" style="width:<?php echo getRating($star['id'])?>%"><!-- will show current rating --></li>
 <?php
 /* we need to generate 'id' for star rating.. this 'id' will identify which data to execute  */
 /* we will pass it in ajax later */
 ?>
 <span id="<?php echo $star['id'];?>">
 <li><a href="javascript:void(0)" title="1 star out of 5">1</a></li>
 <li><a href="javascript:void(0)" title="2 stars out of 5">2</a></li>
 <li><a href="javascript:void(0)" title="3 stars out of 5">3</a></li>
 <li><a href="javascript:void(0)" title="4 stars out of 5">4</a></li>
 <li><a href="javascript:void(0)" title="5 stars out of 5">5</a></li>
 </span>
</ul>
<?php } ?>
</body>
</html>

And this is for update.php

<?php
// connect to database
$dbh=mysql_connect ("localhost", "user", "password") or die ('Cannot connect to the database');
mysql_select_db ("database",$dbh);

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

// get data from tabel
function fetchStar(){
 $sql = "select * from `vote`";
 $result=@mysql_query($sql);
 while($rs = @mysql_fetch_array($result,MYSQL_ASSOC)){
 $arr_data[] = $rs;
 }
 return $arr_data;
}

// function to retrieve
function getRating($id){
 $sql= "select * from vote`` where id='".$id."' ";
 $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($id){
 $text = strip_tags($_GET['rating']);
 $update = "update `vote` set counter = counter + 1, value = value + ".$_GET['rating']."  where id='".$id."' ";

 $result = @mysql_query($update);
}
?>

4. Javascript

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

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

 });
 });

That’s it! hope it works for you :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 (extended) (2267)

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

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

  • Pingback: Tweets that mention jQuery Tutorial : Simple ajax star rating with php | MySandbox -- Topsy.com

  • Pingback: jQuery Tutorial : Simple ajax star rating with php | MySandbox | Drakz Free Online Service

  • Pingback: jQuery Tutorial : Simple ajax star rating with php | MySandbox | Drakz Free Online Service

  • Pingback: jQuery Tutorial : Simple ajax star rating with php | MySandbox | Drakz Free Online Service

  • Pingback: jQuery Tutorial : Simple ajax star rating with php | MySandbox | Drakz Free Online Service

  • Nicholas Smith

    Demo is not working. I get n error. So I hope the code is working….ill try it out

  • ronggur

    @Nicholas : thanks Nicholas, there’s problem with database connection, and i didn’t realize.

  • handsome guy

    Thanks for such an informative tutorial.

  • http://www.webeverythings.com saikiran

    nice rating system

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

    Hi ronggur,

    it’s me again, I just want to make sure that i have thos right.

    i need to add to
    INSERT INTO `vote` (`id`, `desc`, `counter`, `value`) VALUES
    14 (1, ‘star – 1′, 0, 0),
    15 (2, ‘star – 2′, 0,0);
    16 (3, ‘star – 3′, 0,0);
    17 (4, ‘star – 4′, 0,0);

    and so on right.

  • http://sandbox.ronggur.com ronggur

    @HackitZ Yes you are correct, hope it works

    @saikiran Thank You

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

    you are great thanks, do you have any ideas about showing total votes and average votes in plain text beside the stars?

    if not no worries as you have been very helpful and kind to already helping me.

  • http://sandbox.ronggur.com ronggur

    I think the key point is in getRating php function.

    Instead echoing the result, you can return it in an array..
    lets say

    $result['rating'] = $rating;
    $result['voters'] = $total_voters;

    and you can convert and return $result into json format

    and then all you need to do is grab the result in jQuery using jSon function here is info to use json in jQuery http://api.jquery.com/jQuery.getJSON/

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

    Hi again, I’m hoping you help me out with a sql error.

    when i import the sql with the added entries for multiple pages i get this error on import.

    Error

    SQL query:


    – Dumping data for table `vote`

    INSERT INTO `vote` ( `id` , `desc` , `counter` , `value` )
    VALUES 14( 1, ‘star – 1′, 0, 0 ) , 15( 2, ‘star – 2′, 0, 0 ) ;

    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 ’14 (1, ‘star – 1′, 0, 0),
    15 (2, ‘star – 2′, 0,0)’ at line 6

    I have added to the values and it looks like this;

    CREATE TABLE IF NOT EXISTS `vote` (
    `id` int(11) NOT NULL auto_increment,
    `desc` varchar(50) NOT NULL,
    `counter` int(8) NOT NULL default ’0′,
    `value` int(8) NOT NULL default ’0′,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;


    – Dumping data for table `vote`

    INSERT INTO `vote` (`id`, `desc`, `counter`, `value`) VALUES
    14 (1, ‘star – 1′, 0, 0),
    15 (2, ‘star – 2′, 0,0);
    16 (3, ‘star – 3′, 0,0);
    17 (4, ‘star – 4′, 0,0);
    18 (5, ‘star – 5′, 0,0);
    19 (6, ‘star – 6′, 0,0);
    20 (7, ‘star – 7′, 0,0);
    21 (8, ‘star – 8′, 0,0);
    22 (9, ‘star – 9′, 0,0);
    23 (10, ‘star – 10′, 0,0);
    24 (11, ‘star – 11′, 0,0);
    25 (12, ‘star – 12′, 0,0);
    26 (13, ‘star -1 3′, 0,0);
    27 (14, ‘star – 14′, 0,0);
    and so on all the way to 100.

    Hope sopmeone can shed some light on this error.

    Thanks

  • http://sandbox.ronggur.com ronggur

    INSERT INTO `vote` ( `id` , `desc` , `counter` , `value` )
    VALUES 14( 1, ‘star – 1′, 0, 0 ) , 15( 2, ‘star – 2′, 0, 0 ) ;

    there is 14 in there.. it break the sql :D

    it should be only
    INSERT INTO `vote` ( `id` , `desc` , `counter` , `value` )
    VALUES ( 1, ‘star – 1′, 0, 0 ) , 15( 2, ‘star – 2′, 0, 0 ) ;

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

    what are you using to edit the my sql file?
    I’m using notepad++ and it adds the 14, 15, 16 and so on to the file.
    if i open it in notepad (windows default) it does not add the extra numbers.

    Stll getting errors when importing.

    here is my file from notepad,

    CREATE TABLE IF NOT EXISTS `vote` (
    `id` int(11) NOT NULL auto_increment,
    `desc` varchar(50) NOT NULL,
    `counter` int(8) NOT NULL default ’0′,
    `value` int(8) NOT NULL default ’0′,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;


    – Dumping data for table `vote`

    INSERT INTO `vote` (`id`, `desc`, `counter`, `value`) VALUES

    (1, ‘star – 1′, 0, 0),
    (2, ‘star – 2′, 0,0);
    (3, ‘star – 3′, 0,0);
    (4, ‘star – 4′, 0,0);
    (5, ‘star – 5′, 0,0);
    (6, ‘star – 6′, 0,0);
    (7, ‘star – 7′, 0,0);
    (8, ‘star – 8′, 0,0);
    (9, ‘star – 9′, 0,0);
    (10, ‘star – 10′, 0,0);
    (11, ‘star – 11′, 0,0);
    (12, ‘star – 12′, 0,0);
    (13, ‘star -1 3′, 0,0);
    (14, ‘star – 14′, 0,0);
    (15, ‘star – 15′, 0,0);
    (16, ‘star – 16′, 0,0);
    (17, ‘star – 17′, 0,0);
    (18, ‘star – 18′, 0,0);
    (19, ‘star – 19′, 0,0);
    (20, ‘star – 20′, 0,0);
    (21, ‘star – 21′, 0,0);
    (22, ‘star – 22′, 0,0);
    (23, ‘star – 23′, 0,0);
    (24, ‘star – 24′, 0,0);
    (25, ‘star – 25′, 0,0);
    (26, ‘star – 26′, 0,0);
    (27, ‘star – 27′, 0,0);
    (28, ‘star – 28′, 0,0);
    (29, ‘star – 29′, 0,0);
    (30, ‘star – 30′, 0,0);
    (31, ‘star – 31′, 0,0);
    (32, ‘star – 32′, 0,0);
    (33, ‘star – 33′, 0,0);
    (34, ‘star – 34′, 0,0);
    (35, ‘star – 35′, 0,0);
    (36, ‘star – 36′, 0,0);
    (37, ‘star – 37′, 0,0);
    (38, ‘star – 38′, 0,0);
    (39, ‘star – 39′, 0,0);
    (40, ‘star – 40′, 0,0);
    (41, ‘star – 41′, 0,0);
    (42, ‘star – 42′, 0,0);
    (43, ‘star – 43′, 0,0);
    (44, ‘star – 44′, 0,0);
    (45, ‘star – 45′, 0,0);
    (46, ‘star – 46′, 0,0);
    (47, ‘star – 47′, 0,0);
    (48, ‘star – 48′, 0,0);
    (49, ‘star – 49′, 0,0);
    (50, ‘star – 50′, 0,0);

  • http://sandbox.ronggur.com ronggur

    (2, ’star – 2′, 0,0);
    (3, ’star – 3′, 0,0);
    (4, ’star – 4′, 0,0);
    (5, ’star – 5′, 0,0);
    (6, ’star – 6′, 0,0);
    (7, ’star – 7′, 0,0);
    (8, ’star – 8′, 0,0);
    (9, ’star – 9′, 0,0);
    .. and so on ..

    try change the semicolon into comma except the last one

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

    Yeah i tried that and the error is on line 17, this is whats on line 17
    INSERT INTO `vote`(`id`, `desc`, `counter`, `value`) VALUES

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

    ok here is the error that my php shows,

    #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 ‘INSERT INTO `vote`(`id`, `desc`, `counter`, `value`) VALUES (1, ‘star – 1′, 0′ at line 17

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

    Ok my bad, when i changed the ; to , i did a replace and this was changed
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
    to this
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ,

    once i fixed this it worked.

    Thanks ronggur

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

    can the index.php code be put into a .shtml page?

  • Carsten

    Hi, something went wrong with index.html. No votes displayed after voting or reload.
    To solve this problem, insert this 2 lines in starrating.js after: $(document).ready(function() {…

    var cnt = $(‘.star-rating’).size();
    for(i=1; i<=cnt; i++){
    getRating(i);
    }

    Thx for yor work!
    Greatings from germany

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

    OK I figured out what i was doing wrong, i was using this in the page where i wanted the rating.

    Star Rater –
    <ul class='star-rating' id="star-rating-”>

    <li id="current-rating-” style=”width:%”>

    <span id="”>
    1
    2
    3
    4
    5

    Then this is what works for me now.

    1
    2
    3
    4

    5

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

    How do i show the code and not the output of the code?

  • http://sandbox.ronggur.com ronggur

    @Carsten : thanks friend!

    @HackitZ : if you hover the code, you’ll find out three icons appear on the left top :D

  • Maya

    Hi guys,

    Ronggur, thanks so much for this tutorial! However, I have a problem using it on multiple pages (e.g. I have a logo gallery on 4 pages. The first page works great (thanks to Carsten’s addition to the .js), but the others just store the votes correctly, but don’t display them after reload. :(

    Can you please help? Thanks a million!

  • 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 :)

  • MehrD64

    H!
    thanx for great code,
    How to fetch a specific row in database?
    for example i want use this:(1, ‘star – 1′, 0, 0),
    in index.php and i want each row in different pages.

  • http://www.asianborderlands.net/justinerson22 invicta watches for men

    Appreciating the commitment you put into your website and detailed information you present. It’s great to come across a blog every once in a while that isn’t the same old rehashed information. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  • Rashid

    Can you please help me out i use ur code but it is showing me blank stars even it is fine when i m hovering the cursor but now the problem is it is bringing the rating and giving me error when i trace it out i come to know that do is not passing value from javascript, i tried but couldn’t find the solution. Can you help me with this problem. Thanx in advance

  • Anonymous

    eh salah.. yang ini aja yang gue pake buad okecoy tipi…

  • http://sandbox.ronggur.com Ronggur

    Monggo om :D

  • tony

    hi, great code, very simple and functional. I do not know if you have this problem, but when I post a vote, I have to manually refresh the page to see the updated result … the “GetRating” is called, but the screen does not change anything …

  • Pingback: Simple ajax star rating with php | PHP Developer Resource

  • Faizannu

    can u please tell me how to make it like user can’t rate more than one time…

  • Mahshsds

    CHECK DIS