Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- 5 star rating system help


Mr_Cat - 9:55 pm on Dec 15, 2012 (gmt 0)


Hi folks, just getting confused with a star rating script I found online and am trying to implement...

The basic page is thus:



<?php

$votes = mysql_query("SELECT rat_rating FROM fs_nb_ratings WHERE rat_ID = 1");
$votesnr = 0;
$totalvotes = 0;

while($vote = mysql_fetch_array($votes)){
$votesnr ;
$totalvotes = $vote['rat_rating'];
}

if($votesnr == 0){
$rating = 0;
}
else {
$rating = $totalvotes/$votesnr;
}

$roundedrating = floor($rating) + round($rating - floor($rating)) / 2 ;
?>

<div class="star-rating" id="rating1result<?php echo $roundedrating; ?>" style="background-position:0 -<?php echo $roundedrating * 32; ?>px;">
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
<div class="result">
<span style="color:green"><?php echo round($rating,2); ?></span> (<?php echo $votesnr; ?>)
</div>

<script type="text/javascript">

$(function(){

$('.star').mouseover(function (){
var star = $(this).index()+1;
var x =(32 * star);
$(this).parent().css('backgroundPosition','0% ' +(-x)+ 'px');
});

$('.star-rating').mouseout(function (){
var originalresult = $(this).attr('id').split('result')[1];
var y =(32 * originalresult);
$(this).css('background-position','0%' +(-y)+ 'px');
});

});

$('.star').click(function (){
var id = $(this).parent().attr('id').split('rating')[1];
var vote = $(this).index() -1;

$.ajax({
type: "POST",
url:"save-vote.php",
data: 'id='+ id + '&vote='+ vote
});

$(this).parent().removeAttr("id");
$(this).parent().html(" ");
});

</script>



I'm not sure I've put it all together properly and there were a few errors here and there in the tutorial script only some of which were corrected by other folk in comments below it so I did my best to iron them all out but I know bog all about javascript.

save-vote.php reads:



$id = intval($_POST['id']);
$vote = intval($_POST['vote']);

mysql_query("INSERT INTO fs_nb_ratings (rat_ID, rat_rating) VALUES(" . $id . "," . $vote . ")") or die(mysql_error());



...the result is that everything looks fine and it adds appropriate lines to the db, but no matter what star rating you give it it always just adds '3' to the db as the rating number?

it also doesn't give a total rating when the page is refreshed.

Hope that's enough info and makes sense

Any hints appreciated

Cheers


Thread source:: http://www.webmasterworld.com/javascript/4528520.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com