jump to navigation

AJAX Star Rating helper September 7, 2006

Posted by rossoft in CakePHP.
trackback

An AJAX Star Rating Helper based on link1 and link2.

Installation instructions.
1) Download + install CJS Templates version 2.1 from cakeforge snippets
2) Copy star CSS file to app/webroot/css/star_rating/star_rating.css
  and add the line “overflow: hidden;” to .star-rating
3) Copy star Image file to app/webroot/css/star_rating/alt_star.gif
4) Copy the helper to app/views/helpers/star_rating.php

Usage example: include the helper and in your view file:

echo $starRating->display(‘Post/rating’,”/posts/rate/$id”)

It will create a star rater for the field Post/rating. An AJAX call will be made to /posts/rate/$id/$rate_value ( /$rate_value is appended to the CakeUrl that you pass to display function )

<?php
/**
 * Star Rating Helper
 *
 * @author RosSoft
 * @version 0.1
 * @license MIT
 *
 * @link http://www.naffis.com/blog/articles/2006/08/31/rails-ajax-star-rating-system
 *
 * Copy star CSS file to app/webroot/css/star_rating/star_rating.css
 * and add the line “overflow: hidden;” to .star-rating
 *
 * @link http://komodomedia.com/blog/samples/star_rating/example2.htm
 *
 *
 *
 * Copy star Image file to app/webroot/css/star_rating/alt_star.gif
 * http://komodomedia.com//blog/samples/star_rating/alt_star.gif
 *
 * @package helpers
 *
 * Usage example: include the helper and in your view file:
 * echo $starRating->display(‘Post/rating’,”/posts/rate/$id”)
 * It will create a star rater for the field Post/rating. An AJAX call
 * will be made to /posts/rate/$id/$rate_value
 * ( /$rate_value is appended to the CakeUrl that you pass to display function )
 */

class StarRatingHelper extends Helper
{
    var $helpers=array(‘Head’,’Util’,’Page’);

    /**
     * Pixels of star width
     */
    var $_star_width=25;

    var $ratings=array(
        array(    ‘title’=>’1 estrella de 5’,
                ‘class’=>’one-star’),

        array(    ‘title’=>’2 estrellas de 5’,
                ‘class’=>’two-stars’),

        array(    ‘title’=>’3 estrellas de 5’,
                ‘class’=>’three-stars’),

        array(    ‘title’=>’4 estrellas de 5’,
                ‘class’=>’four-stars’),

        array(    ‘title’=>’5 estrellas de 5’,
                ‘class’=>’five-stars’)
        );

    function _width($score)
    {
        if ($score >=0 && $score <=5)
        {
            $width = $score * $this->_star_width;
        }
        else
        {
            $width=0;
        }
        return $width;
    }

    /**
     * Creates a star rater.
     * @param mixed $value Model/field of the actual rate or the rate in float [0..5]
     *     Examples:
     *   3.5
     *   Post/rate
     * @url Url to be called through AJAX
     *  Example: if you need to rate the post id 3
     *     $url=’/post/rate/3′
     *  Then when clicked the 5 stars, the url called will be /post/rate/3/5
     * @return string The html code for the star rater
     */
    function display($value,$url)
    {
        static $index=0;
        $index++;

        $this->Head->css(‘star_rating/star_rating’);
        if (!is_numeric($value))
        {
            $score=$this->Util->retrieve_value($value);
            $id=$this->Util->fieldname_to_formid($value);
        }
        else
        {
            $score=$value;
            $id=”star_$index”;
        }
        $width=$this->_width($score);
        ob_start();
        ?>
        <ul class=’star-rating’ id='<?php echo $id?>’>
            <li class=’current-rating’ style=’width:<?php echo $width?>px;’></li>

            <?php for ($i=0;$i<5;$i++):?>
                <li><a href=’#’ onclick=”return false;” title='<?php echo $this->ratings[$i][‘title’]?>’ class=’star <?php echo $this->ratings[$i][‘class’]?>’><?php echo($i+1)?></a></li>
                <?php echo $this->Page->event(“#$id .{$this->ratings[$i][‘class’]}”,’click’,$this->Page->remote_url($url . ‘/’ . ($i+1),array(),false))?>
            <?php endfor;?>
        </ul>
        <?php
        return ob_get_clean();
    }

    /**
     * Change the number of stars of a displayed star rater
     * @param string $dom_id The DOM ID of the star rater to change
     * @param float $score The score from 0 to 5
     *
     * @return string HTML-Javascript Code
     */
    function change($dom_id,$score)
    {
        $width=$this->_width($score);
        $css=”#{$dom_id} .current-rating”;
        $js=”_elem.style.width='{$width}px’;”;
        return $this->Page->for_each($css,$js);
    }

    /**
     * Creates an effect of highlight in a displayed star rater
     * @param string $dom_id The DOM ID of the star rater to change
     * @param float $duration Duration of the effect in seconds
     *
     * @return string HTML-Javascript Code
     */
    function highlight($dom_id,$duration=0.3)
    {
        return $this->Page->effect(
            array(    “#$dom_id .current-rating”,
                    “#$dom_id”)
            ,’Highlight’,array(‘duration’=>$duration));
    }

}
?>

Advertisements

Comments»

1. Riky Kurniawan - September 10, 2006

what an useful helper..thanx Ros

2. rockdeman - September 11, 2006

Hello Ros, is this where we can find the snippets? http://cakeforge.org/snippet/detail.php?type=packagever&id=38 It says here ‘CjsView’ V0.21 (do you mean V0.21 instead of V2.1?) Also it says RJS Templates – not CJS? I am new to this it’s kind of confusing but it seem this is a really cool helper.

3. rockdeman - September 11, 2006

I am getting a bunch (wel.. 5) of javascript errors, I think 1 for every star : ‘$$ is not defined’
the javascript looks like this:

1
$$(‘#ClipRating .one-star’).each(function(_elem) { Event.observe(_elem, “click”, function(event){ new Ajax.Updater(‘page_container’,’/myapp/items/rate/481/1′, {asynchronous:true, evalScripts:true, requestHeaders:[‘X-CJS-Templates’, ‘1’, ‘X-Update’, ‘page_container’]})}, false); });

4. rossoft - September 11, 2006

@rockdeman:
1.
the URL of snippets that you’ve post is correct. I’ve changed the name of that a lot of times…so it’s very confusing now. The real name is CJS Templates, follow the installation instructions.

2. $$() is a function of prototype library. You will need to download prototype + scriptaculous and include them in your layout. It must be explained in the manual.

3. The response page is javascript. If you have
function myrate($id,$rate)
{
$this->view=’Cjs’;
(….)
}
then the view template is the file myrate.cjs and it is ONLY javascript (it does not replace directly your div, you must replace the divs explicitly with $page helper)

5. rockdeman - September 12, 2006

Ah Ros so: I did already use prototype.js V1.4.0 – which is the latest official release (see http://prototype.conio.net/dist/prototype-1.4.0.js) this version does not have fuction $$() … however scriptalicous V1.6.4 requires 1.5.0_rc1 version of Prototype which has function $$ … see http://script.aculo.us/downloads . Thanks for the update!

6. tyler - September 23, 2006

Works great. You can imagine my surprise when i googled for ‘star rating helper cakephp’ and came here! I figured for sure i’d have to roll my own.

Word of warning: If you are importing this into a site with an existing CSS, then be aware that previously defined CSS definitions (especially on ul and li) will cause this to render incorrectly. Took me about an hour to troubleshoot.

7. tiberth - October 6, 2006

I tried to update the view with the new rating that the user chooses but I am having problem getting it work. The database has been updated though.

I tried to enclose the star rater within and
in my cjs file i tried
echo $page->replace_html(“#rate”,$starRating->display($value,”/post/rate/$id”)) but it doesn’t seem to work. I guess it got to do with _enclose detecting that it is a CjsView and did not enclose with a javascript tag.

What should be done to get the star rater to display correctly after the user has updated the rating? I’m not sure if this is the correct way to do it in the first place….please advice…..thanks

8. mtuabor - October 18, 2006

yes, I also need an answer for previous question. suggest pleaes.

9. rossoft - October 18, 2006

@mutabor, @tiberth: You can update the value in cjs view with
echo $starRating->change(‘star_1’,5); (where star_1 is the DOM ID of the generated star rater.
$starRating->display(4,$url) generates dom id “star_1” . $starRating->display(‘Model/field’,$url) generates dom id ModelField. Put that ID in change() call

10. mutabor - October 18, 2006

Thank you, it works 🙂

11. tiberth - October 20, 2006

It works like a charm, Thank you very much

12. Andrzej Borkowski - October 22, 2006

i have a problem witch helper in notepad and zendeditor becouse
>> ” ’ _width($score);
$css=”#{$dom_id} .current-rating”;
$js=”_elem.style.width=’{$width}px’;”;
return $this->Page->for_each($css,$js);
}
someone have file witch good code helper ?

13. rossoft - October 23, 2006

@Andrzej: I don’t understand what’s your problem with the editor

14. Ritesh - October 29, 2006

hi,

I am interested in using star rating system but have never used cjs template before. I am not sure what is cjs template. Is there any instruction on it. I tried googling but always came back to this page only.

Thanks

15. rossoft - October 29, 2006

@Ritesh: CJS Templates are my version of “RJS Templates”, the Rails original version. See google for it.

If you haven’t used CJS Templates, then try doing my own log tutorial, search for “Blog tutorial” in my blog.

16. Justkez.com | CakePHP Ajax Star Rating - November 28, 2006

[…] Asides CakePHP Ajax Star RatingThe MX Revolution is mine!Breastfeeding woman kicked off flightJustkez gets a sideblogInnocent smoothies get winter hats […]

17. anjali - December 2, 2006

I am new to this CJS templates, but i want to use this helper to my application. Can you please explain me the step-by-step procedure to implement this. I am working in Cake Php only.

18. rossoft - December 2, 2006

@anjali: first go to here http://cakeforge.org/snippet/detail.php?type=packagever&id=38 and download all the files. There is a file with the instructions for installing Cjs Templates.
Then follow this post for installing de Ajax Star Rating, it must be easy, good luck 🙂

19. rossoft - December 2, 2006

@anjali: if you want more info about cjs, read my blog tutorial in pdf, I use it there

20. anjali - December 5, 2006

thanks , surely i will try it and if i found any difficulty I will cum bak.

21. anjali - December 12, 2006

Thanks a lot.

I implemented this according to the given instructions, i am facing 2 problems only:

1) It gives a javascript error on :

Event.observe(window,’load’,function() { new Insertion.Bottom($(document.body),”);
});

2) when I click on a star it doesn’t go to any action.

Can you please guide me what i should do now.

22. Alex - December 18, 2006

My Firefox (2.0) marks the whole space between left div-box model and anchor when clicking a star. thats not nice. how to change this?

and is there a possibility to load star_rating as helper for only one controller (not in app_controller.php) without repeating all other helpers from app_controller?

big thx

23. Alex - December 18, 2006

…and please can you explain a little bit (to a CJS noob) how to update the stars with the new value right after clicking it?

🙂

24. rossoft - December 18, 2006

@alex:
1) I don’t know how to hide this mark 😦

2) In my version of cake (1.1.7), if you put some helpers in your AppController, and some others in your controller, it loads all of them (union)

3) In the view of the response page, put
echo $starRating->change(’star_1′,5); (where star_1 is the DOM id of the star rater, it can be other if you’ve used Model/field syntax in the creation)

25. Eppo - January 21, 2007

Is there a working sample wich I can download. Because I dont get it at alll

26. lukemack - February 27, 2007

Please can you provide a download of the helper file? cutting and pasting into Zend doesn’t work – you get lots of strange characters – presumably because you are using a spanish characterset or something.

thanks,

lukemack.

27. Get Started With AJAX in CakePHP « Ahsan’s Laboratory - March 16, 2007
28. Midnight Oil » Blog Archive » Ajax CSS Star Rating with acts_as_rateable - May 4, 2007

[…] WordPress Plugin […]

29. Siddharth - May 21, 2007

Hi,

I did everything you specified. And then modified my database table to add a column ‘rating’ so that rating may get stored there. There are no warnings/notices/errors (Debug Mode is set to 3), but its not working. The ratings don’t get updated in the database. Infact default is set to NULL, but it becomes 0 and stays like that. The rating in the view also does not change after clicking on a star. It remains unrated. On hovering over a star, it shows this link “…/view/2#” where ‘2’ is the id of the of the item which is on the view (Isn’t it supposed to show something like /rate/id ?).
How do I get this to work?
In case you need any more details, let me know. This is a really cool app and I would like to get it running.

30. Siddharth - May 21, 2007

Also, looking at Tyler’s post, I do have a pre existing CSS (the CSS which comes default with Cake). But I don’t understand why it may cause rating to not get updated in the database.

31. banesto - July 5, 2007

its because of the cakephp version

32. Maurizio P. - September 7, 2007

I followed instructions and i can see stars appear under as it pass over.
Newbie question : how is the code of php function that manage the assignment of rating through AJAX ?
Thx a lot

33. bkr hypotheek - September 18, 2007

Thanks for all the info for the star rating with AJAX.
It helped me alot, yeah yeah I know i have to read better 😛

34. Bryn F - September 19, 2007

Does anybody have this working with Cake v1.2?

Also for those that are having trouble copying/pasting the code, you need to search and replace the ` characters (and the one going the other direction as well as the double quote versions) with ‘ and ” respectively.

35. Bryn F - September 19, 2007

for people getting the Event.observe(window,’load’,function() { new Insertion.Bottom($(document.body),”);
});

error, I fixed that by making moving the echo $head->registered function in the layout after the javascript->links to prototype and scriptaculous

link(‘prototype.js’); ?>
link(‘scriptaculous.js?load=effects’); ?>
registered() // this is for the ajax star rating helper?>

36. Bryn F - September 19, 2007

I get a missing } in XML expression

display(‘Boutique/Rating’,$url);
$newsr = $starRating->change(“BoutiqueRating”,3);
echo $page->replace_html(“BoutiqueRating”, $newsr);
?>
the response from the ajax call is:

$$(‘BoutiqueRating’).each(function(_elem

) { Element.update(_elem,unescape(“%3Cscript type=\”text\/javascript\”>$$(‘#BoutiqueRating .current-rating’

).each(function(_elem) { _elem.style.width=’75px’; });%3C\/script>\r\n”)); });

it goes away if I set enclose to false on replace_html but it still doesn’t update the stars (doesn’t seem to have any effect at all

my rate.cjs file after getting rid of js error is :

display(‘Boutique/Rating’,$url);
$newsr = $starRating->change(“BoutiqueRating”,3);
echo $page->replace_html(“BoutiqueRating”, $newsr, false);
?>

the response from the ajax call is:
$$(‘BoutiqueRating’).each(function(_elem) { Element.update(_elem,unescape

(“%3Cscript type=\”text\/javascript\”>$$(‘#BoutiqueRating .current-rating’).each(function(_elem) { _elem

.style.width=’75px’; });%3C\/script>\r\n”)); });

I’m stuck, can anybody help me?

37. Jean-Philippe - September 23, 2007

I’m new to php and new to cake, coming from Java. Got the 4 steps done correctly. However, the following seems a little short to me:

“Usage example: include the helper and in your view file: echo $starRating->display(’Post/rating’,”/posts/rate/$id”)”

While reading the comments, I realised there was probably a lot more to do.

Right now in the view I do
loadView(‘helpers/star_rating’);
$starRating = new StarRatingHelper ;
echo $starRating->display(“Magazine/rating”,”/magazines/rate/$id”);

and get :
Undefined variable: id [CORE\app\views\magazines\index.thtml, line 14]
Undefined property: StarRatingHelper::$Head [CORE\app\views\helpers\star_rating.php, line 86]

Anyone can detail more how to ‘include the helper’ and what I am missing?
Thanks for the help

38. Bryn F - September 24, 2007

Jean Philippe, in your magazines controller you probably have to set the $id variable
something like this
$this->set(‘id’, $id));

39. Bryn F - September 24, 2007

There’s another star rating snippet for cakephp here http://www.reversefolds.com/articles/show/rating2
that doesn’t require the use of CJS and is a little simpler (for me) to get going. I’m not sure about the relative technical merits of the two approaches

40. Affiliate Elite - October 18, 2007

hi
this: var $ratings=array(
array( ’title’=>’1 estrella de 5′,
’class’=>’one-star’),

array( ’title’=>’2 estrellas de 5′,
’class’=>’two-stars’),

array( ’title’=>’3 estrellas de 5′,
’class’=>’three-stars’),

array( ’title’=>’4 estrellas de 5′,
’class’=>’four-stars’),

array( ’title’=>’5 estrellas de 5′,
’class’=>’five-stars’)
is giving me some errors
any ideas ?

41. Nik Chankov - October 22, 2007

Thanks Rossoft,
this will save a lot of work to me. I need to use such helper in one of my projects.

Cheers!

42. Giga Promoters Blog » 10 Best CakePHP snippets for Web2.0 development - October 24, 2007

[…] AJAX Star Rating: This is a great one, lets you implement the rating system with your Cake application very fast and […]

43. JohnQ - October 25, 2007

Another ajax rating and review solution: http://www.rating-system.com
Lightweight and free and crossplatform

44. fil - November 29, 2007

hey.

with me its 3 people who struggled because of copy and paste of the code. please provide a download.

another thing i cant get working is, that my cake screws up real bad with including these head, etc. helpers..

45. mike - December 16, 2007

This really helped me. Thanks for you help 🙂

46. Dean - February 28, 2008

This is a great helper and I was wondering if it was fully compatiable with CakePHP 1.2?

47. AddressMan - March 28, 2008

good work i will use it in my dir to rate websites, thanks!

48. jWBZP - June 26, 2008

This Is Pretty Much The Best SiteDo You Have Other Sites?, canadian free online dating services, canadian free online dating services, fbh,

49. Training Guy - July 3, 2008

Thanks for the script rossoft!
Are there any full fledged website scripts running on cakephp which include the rating functionality?

50. bkr hypotheek - July 9, 2008

bkr hypotheek…

Interesant artikel. Kan ik dit op mijn blog plaatsen? gr, Remcowoudstra…

51. name - September 1, 2008

Hello!,

52. adding comment in picture - November 29, 2008

You Should try this too!

53. christmas dad gift mom - November 29, 2008

Thank You Very Much For Showing This InfoCan You Look At THis?

54. Top Shot - December 8, 2008

Cool, thanks!

55. Ratenkredit Editor - March 12, 2009

Thanks for your help! I am just implementing the script to my website for a credit test system where people can share their experiences.

You find the ajax star rating system here:
http://www.ratenkredit.org/ratenkredite_test.html

56. Hypotheek - July 8, 2009

Im new at this so i also get a lot of errors. I agree with Eppo. Could you maybe provide us with a download of the files? I cant seem to make it work with just copying and pasting the codes. tnx!

57. [PRONIQUE] CakePHP Developer Links - July 23, 2009

[…] AJAX Star Rating helper « RosSoft […]

58. RenteSpotter - August 5, 2009

Hello RosSoft,

Thank you very much.

Greetings, RenteSpotter

59. (Best Show)Watch - September 7, 2009

“Hi:

Two things

1) I’d like your permission to (re)print your article on “The Goode Family”
for our website

2) I was hoping we could use your ‘scribing’ talent for our website.

The Best Shows Youre Not Watching (dot) com [all one word]

‘The Clone Wars’ is one of our featured shows. We’re hoping to round up a few people who can occasionally contribute perspective (via an article/blog) on the shows – maybe a recent episode, future direction, plot shortcomings etc.

What’s in it for you?
Primarily a larger audience back channeled to your blog. We don’t pay but the site has a lot of promise and we’re pretty excited about getting it off the ground. Let me know what you think.

Thanks

60. hypotheekrente - September 11, 2009

Yes a downloadfile would be nice. Does anyone have one?

61. geld lenen - September 16, 2009

Nee kun je niet op je blog plaatsen

62. Hypotheken.net - September 17, 2009

Nice article !

63. vinska klet - November 9, 2009

Here here. Very nice.

64. AJAX Star Rating Helper based (Cakephp) « Cakephp « Framework « Codes php – Share your php snippets - April 28, 2011

[…] https://rossoft.wordpress.com/2006/09/07/ajax-star-rating-helper/ [!] Report this snippet Processing your request, Please […]

65. Airco plaatsen - January 5, 2012

Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.

66. Rent apartments - January 15, 2014

Thanks, it works. Nice report

67. paletas serranas - March 14, 2014

Excellent goods from you, man. I have understand your stuff previous to and you are just extremely wonderful.
I actually like what you have acquired here, certainly
like what you’re stating and the way in which you say it. You make it entertaining and you still take care of to keep it sensible. I can not wait to read far more from you. This is actually a great web site.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: