I am still in beginner's level of WordPress and PHP. I already doing my research in stackoverflow but because of my low-level understanding, I can't find the solution for the problem I have.
I use WordPress as CMS for my website. I use PHP echo
for showing the average rating value of a user review plugin. It shows fine. But after a visitor insert his/her own rating and click submit button, the average rating value didn't update until the page is refreshed. How to automatically update the average rating value after the submit button clicked without having to refresh the page?
<script type="text/javascript">
var userRating = <?php echo rmp_get_avg_rating( $postID ); ?> ;
document.getElementById("div-rating").innerHTML = userRating;
</script>
This is the submit button class created by the plugin to trigger User Submission.
rmp-rating-widget__submit-btn rmp-btn js-submit-rating-btn rmp-rating-widget__submit-btn--visible
This is the PHP function I need to echo.
public function load_results() {
if ( wp_doing_ajax() ) {
// array with vote count, ratings and errors
$data = array(
'voteCount' => false,
'avgRating' => false,
'errorMsg' => '',
);
$post_id = intval( $_POST['postID'] );
$nonce = isset( $_POST['nonce'] ) ? $_POST['nonce'] : false;
// security check
if( ! $post_id ) {
$data['errorMsg'] = esc_html__( 'You cannot rate a web page without an id!', 'rate-my-post' );
echo json_encode( $data );
die();
}
$nonce_check = $this->has_valid_nonce( $nonce );
if( ! $nonce_check['valid'] ) {
$data['errorMsg'] = $nonce_check['error'];
echo json_encode( $data );
die();
}
$vote_count = rmp_get_vote_count( $post_id );
$sum_of_ratings = rmp_get_sum_of_ratings( $post_id );
$average_rating = rmp_calculate_average_rating( $sum_of_ratings, $vote_count );
if ( $average_rating ) { // post has been rated
$data['voteCount'] = $vote_count;
$data['avgRating'] = $average_rating;
} else { // no ratings so far
$data['voteCount'] = 0;
$data['avgRating'] = 0;
}
echo json_encode( $data );
};
die();
}
Thank you for your help.