Hello Friends,
If you are looking to implement star rating with Ajax. Please find the below example for the same:
1) Open your HTML file and write the code below to display stars:
NOTE :: I have attached the primary key with div-id(tutorial-id; ?>)
<table class="demo-table">
<td style="width:12%" valign="top" align="center">
<div id="tutorial-<?php echo $results[$i]->id; ?>">
<input type="hidden" name="rating" id="rating" value="<?php echo $results[$i]->rating; ?>" />
<ul onMouseOut="resetRating(<?php echo $results[$i]->id; ?>);">
<?php
// Display 5 stars with the below code
for($j=1;$j<=5;$j++) {
$selected = "";
if(!empty($results[$i]->rating) && $j<=$results[$i]->rating) {
$selected = "selected";
}
?>
<li class='<?php echo $selected; ?>' onmouseover="highlightStar(this,<?php echo $results[$i]->id; ?>);" onmouseout="removeHighlight(<?php echo $results[$i]->id; ?>);" onClick="addRating(this,<?php echo $results[$i]->id; ?>);">★</li>
<?php } ?>
<ul>
</div>
</td>
</table>
2) Place the below code in your Jquery part ::
<script type="text/javascript">
function highlightStar(obj,id) {
removeHighlight(id);
$('.demo-table #tutorial-'+id+' li').each(function(index) {
$(this).addClass('highlight');
if(index == $('.demo-table #tutorial-'+id+' li').index(obj)) {
return false;
}
});
}
function removeHighlight(id) {
$('.demo-table #tutorial-'+id+' li').removeClass('selected');
$('.demo-table #tutorial-'+id+' li').removeClass('highlight');
}
function addRating(obj,id) {
$('.demo-table #tutorial-'+id+' li').each(function(index) {
$(this).addClass('selected');
$('#tutorial-'+id+' #rating').val((index+1));
if(index == $('.demo-table #tutorial-'+id+' li').index(obj)) {
return false;
}
});
$.ajax({
type: "POST",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { 'action':'custom_add_rating', 'id':id, 'rating': $('#tutorial-'+id+' #rating').val() },
});
}
function resetRating(id) {
if($('#tutorial-'+id+' #rating').val() != 0) {
$('.demo-table #tutorial-'+id+' li').each(function(index) {
$(this).addClass('selected');
if((index+1) == $('#tutorial-'+id+' #rating').val()) {
return false;
}
});
}
}
</script>
3) Open your PHP FILE where you would like to call ajax to update records in database and make the below code:
function custom_add_rating_callback(){
global $wpdb;
$rating = array('rating' => $_POST["rating"]);
echo $wpdb->update('wp_connections', $rating, array('id' => $_POST["id"]));
echo $wpdb->last_query;
}
0 Comment(s)