$rating->update_rating($userrating); } else { // Delete the rating if the user set to Rate. $options = new stdClass(); $options->contextid = $context->id; $options->component = $component; $options->ratingarea = $ratingarea; $options->userid = $USER->id; $options->itemid = $itemid; $rm->delete_ratings($options); } // Try to update grades in case grading by entries. $df->grade_manager->update_calculated_grades(array('userid' => $rateduserid)); // Need to retrieve the updated item to get its new aggregate value. $item = new stdClass(); $item->id = $itemid; // Most of $ratingoptions variables were previously set. $ratingoptions->items = array($itemid => $item); $ratingoptions->aggregate = array(RATING_AGGREGATE_AVERAGE, RATING_AGGREGATE_MAXIMUM, RATING_AGGREGATE_MINIMUM, RATING_AGGREGATE_SUM); $items = $rm->get_ratings($ratingoptions); $firstitem = reset($items); $aggr = $field->get_rating_display_aggregates($firstitem->rating); // Result. $result->success = true; $result->ratingcount = $aggr->count; $result->ratingavg = $aggr->avg; $result->ratingmax = $aggr->max; $result->ratingmin = $aggr->min; $result->ratingsum = $aggr->sum; $result->itemid = $itemid; echo json_encode($result);