Search code examples
phpjqueryraty

jQuery Raty - First value is null passing from PHP


I am trying to use the jQuery raty plugin to display multiple ratings on the same page with a value stored in a php variable. The following is the code I am using:

<script>
$('.star').raty({score: <?php echo $slide['Article']['rating']; ?>});
</script>
<div class="star"></div>

The problem I am having is that the first rating is empty and then all the ratings after are 1 off due to the first not populating correctly. I'm not a jQuery guy so i'm not quite sure where I am going wrong if the variables after the first populate. Any help would be much appreciated.


Solution

  • Cast it to float:

    $('.star').raty({
        score: <?php echo (float) $slide['Article']['rating']; ?>
    });
    

    This way a NULL value will produce 0 instead of an empty string which will cause js errors, and has the extra benefit of making sure the value is 100% safe to use in your javascript. Other invalid values will also be 0 after the cast.