John Davidson

javascript - jQuery star rating plugin doesnt return correctly amount of stars

0 comments
Message:


I'm making a rating system to rate a post using 5 stars. I use the jQuery bar plugin for this (jQuery bar plugin).


Users can vote posts from 1 to 5. The data is stored in the database. After someone votes the stars will be disabled and show the amount of stars the user rated.


Rating is correctly stored in database and after user rate e.g. 3 stars It display 3 stars and console.log currentRating show correctly 3 stars, but when user go other page and go back to the post that rated it won't return the right amount and it will just show 1 star. When someone other user go that post that someone else rated it displays 1 star always.


So what I've done wrong or is barrating lib supposed work that way?


How I can always display right amount stars as active and when user come back or ctrl+f5 right amount stars displayed?


Code:


    $rating_res = "SELECT * FROM post_rating
WHERE post_id = " . $id . " AND userid = " . $userid;

$rating_arr = sql_query($rating_res);
$getRating = mysql_fetch_array($rating_arr);
$rating = $getRating['rating'];

$avg_res = "SELECT ROUND(AVG(rating), 1) as numRating
FROM post_rating WHERE post_id=".$id;

$avgresult = sql_query($avg_res);
$fetchAverage = mysql_fetch_array($avgresult);
$numRating = $fetchAverage['numRating'];

if ($numRating <= 0) {
$numRating = "N/A";
}

<select id='rating_<?php echo $id; ?>' name="star_rating_option"
class="rating" data-id='rating_<?php echo $id; ?>'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Rating: <span id='numeric_rating_<?php echo $id; ?>'><?php echo $numRating; ?></span>

And here is jquery barrating part:


 $(document).ready(function() {
currentRating = $(".rating").val();
console.log(currentRating);

$('#rating_<?php echo $id; ?>').barrating('set',<?php echo $rating; ?>);
});

$(function () {
$('.rating').barrating({
theme: 'fontawesome-stars',
initialRating: $(this).data('current-rating'),
//initialRating: currentRating,

onSelect: function (value, text, event) {

var el = this;
var el_id = el.$elem.data('id');

if (typeof (event) !== 'undefined') {
var split_id = el_id.split("_");
var post_id = split_id[1];
$.ajax({
url: './rate.php',
type: 'post',
data: {
post_id: post_id,
rating: value
},
dataType: 'json',
success: function (data) {
var average = data['numRating'];
$('#numeric_rating_' + post_id).text(average);
}
});
}
}
});
});


My Answer:
mysqli_query($conn, "SELECT * FROM ratings WHERE post_id = $post_id");
$rating_row = mysqli_fetch_assoc($rating_res);
$currentRating = $rating_row['rating'];



Rate this post

4 of 5 based on 5509 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us