Search code examples
jqueryraty

How can I define raty "score" variable to pass to php script?


I am trying to implement raty into a website. I have got the plugin working apart from one slight problem. I cannot manage to store the rating value into my database, because I cannot manage to pass the score variable to my php script. This is my code:

<div id="star" onclick="javascript:rateMe()"></div><br /><br />
<div id="hint"></div><br />
<script type="text/javascript" src="scripts/js/jquery.raty.min.js"></script>
<script type="text/javascript">

$('#star').raty({
 half  : true,
 number: 10,
 score : 5,
 cancel     : true,
 cancelHint : 'none',
 target     : '#hint',
 targetKeep   : true
});

</script>

and my post function to get the data to my database is:

function rateMe(score) {
                $.post('scripts/php/rater.php',{score:score, userid:<?php echo $memid; ?> },function(data){alert(data+' Score = '+score);
                });         
} 

My PHP script is fine, and the data is being posted to it apart from the score itself! Somewhere in the above code I am missing something. My alert returns all of the variables correctly, apart from those referring to the score, which are null and the final part of my alert is returned as "Score = Undefined". I have tried using onclick="javascript:rateMe(score)" but this fails to even post the data, and I get no alert.

I want to know what I am doing wrong. I have tried to declare the score variable outside of the function, I have added a click event to the function, I have tried renaming the score variable as in the documentation, I've tried placing the function within $(document).ready function() {...} tags, along with the raty part of the code...to no avail. Any help would be appreciated...I am a novice with javascript and I am searching through my cookbooks but cannot find an answer. If anyone can help me to understand why the score variable is not being passed to the php script I will be eternally grateful. Thanks :)


Solution

  • Try putting the click handler in the options of the raty object:

    <div id="star"></div><br /><br />
    <div id="hint"></div><br />
    <script src="lib/jquery-1.7.2.js" type="text/javascript"></script>
    <script type="text/javascript" src="lib/raty.js"></script>
    <script type="text/javascript">
    
        $('#star').raty({
            half  : true,
            number: 10,
            score : 5,
            cancel     : true,
            cancelHint : 'none',
            target     : '#hint',
            targetKeep   : true,
            click: function(score, evt) {
                $.post('raty.php',{score:score, userid:0 },
                        function(data){
                            alert(data+' Score = '+score);
                });
            }
        });
    </script>