Code to Calculate Average Rating Not Working...?

I carefully copied and pasted the code provided in the Wix Code Tutorial (“Capturing and Displaying Ratings”) to my page, then edited it to reflect my personal field keys, etc, but not everything is working and I don’t know where I went wrong. The review input elements are coded to be sent to my Venues_Reviews dataset upon clicking ‘#button2’. Almost everything works (Venue Name, Reviewer’s Name, Wedding Date, Rating & Comments) EXCEPT the part where it’s supposed to input the average rating (field key: averageRating), number of ratings (field key: totalReviews) and total ratings (field key: totalRatings). After doing a test submission, these fields are left empty. I’ve pasted my code below, can anyone tell me if there’s an error somewhere?

export function button2_click(event) {
$w(“#dataset1”).onReady(() => {
// get the current item from the dataset
const currentItem = $w(“#dataset1”).getCurrentItem();

// get the current average rating, number of ratings, and
//total ratings for the current dataset item
const average = currentItem.averageRating;
const count = currentItem.totalReviews;
const total = currentItem.totalRatings;

// get the new rating from the ratings input
const newRating = $w(‘#ratingsInput1’).value;

// calculate the new average rating based on the current
//average and count
const newAverageLong = (total + newRating) / (count +1);
// Round the average rating to 1 decimal point
const newAverageShort = Number.parseFloat(newAverageLong).toFixed(1);

// set the dataset fields to the new average, total
// ratings, and number of ratings
$w(‘#dataset1’).setFieldValues({
‘venueName’: $w(‘#input2’).value,
‘reviewersName’: $w(“#input1”).value,
‘weddingDate’: $w(“#datePicker1”).value,
‘rating’: $w(“#ratingsInput1”).value,
‘comments’: $w(“#textBox1”).value,
‘averageRating’: newAverageShort,
‘totalReviews’: total + newRating,
‘totalRatings’: (count + 1)
});

// save the dataset fields to the collection
$w(‘#dataset1’).save()
. catch ((err) => {
console.log(‘could not save new rating’);
});
});
}

Hi Chanel,
Can you please share a link to your site and specify the name of the page?
Roi.

Hi Roi,
Thank you for your reply, unfortunatel, I no longer am able to attach the rating display element to my repeater. When I sent a help request to Wix, they said it is not possible to attach a rating display to a repeater. I know I was able to in the past, but now that I can no longer do so, I’m at a lost as to how I should display the ratings from my database collection. Trying to show the rating average, therefore, is a moot point right now, unless Wix allows rating displays to be attached to repeaters again…

Hi Chanel and Roi,

I am having the same issue, I am trying to add a rating input and display element to a repeater on my site. However it only works for the first item in the repeater. I cannot rate and store ratings for other items. Is this a genuine limitation of the code editor or are we missing something?

Chanel, did this ever work for you?

Thanks in advance,
George

Hi George, after days and days of trying, I’ve FINALLY been able to attach the rating display to my repeaters. Hopefully you can too now. Next I’ll need to take a look at how to collect & actually display full reviews and calculate averages…

Hi Chanel. I was able to make this work a while ago. Being new to the platform I realized if you want something done that is not available in the platform, you need to use Wix code. The key for my challenge was not to use a dataset connected to my repeater. That would not allow you to rate individual items (input) but only to display individual ratings (output). Instead I read and display the items on a repeater programmatically using code in the backend. I am not sure why this is not a feature using the Editor, it would help a lot. If anyone else is stuck in this challenge too, I don’t mind creating a post with my solution.

Best,
George

Hi George and Chanel,

Would either of you be able to share a solution that worked for you? I have encountered this exact problem and have not been able to solve it.

Thank you,

Mike

Unfortunately, I STILL do not know how to calculate ratings. I literally spend the last 5 hours working through the Wix tutorial again numerous times, plus I’ve been scouring online for other explanations/examples to no avail. While playing around with my code, there were a few instances I ‘magically’ was able to have numbers appear in the fields for my total number of reviews, new ratings average, etc BUT I no longer have any numbers in these areas when submitting my ratings via code (Could there be a bug in the Wix system…? I know this was why the ratings display wasn’t working a while back). Basically, the code properly saves information into my dataset pertaining to user name, rating, comments BUT I cannot get the code to actually calculate the AVERAGE or TOTAL number of ratings!!! GRRR, so frustrating!!!

If anyone, ANYONE at all, can share an example where they’ve successfully done this with their code, I (and many others, I’m sure) would be immensely grateful. As a novice, I really need to see the actual code with some clear explanations. I want site visitors to be able to leave a review similar to how Yelp does it - where the company name, their name, their comments, their rating & a picture are shared in their review (submitted via a button - not ‘automatically’ upon change event, as in the Wix example).

THANK YOU TO ANYONE WHO CAN HELP WITH THIS!!!

Hi Mike and Chanel,

I think you might be solving a slightly different problem than me. My code allows a user to search and rate an item at real-time without using a dataset but instead relying on a repeater and backend code. Behind the scenes I have an “Items” collection and a “Ratings” collection where I keep track of User A rated Item B a rating score of C. I am not currently calculating any averages or totals and displaying them but I think this is something doable with my setup. Let me know if this is something you would find useful.

Best,
George Zoto

Hi there,

Has anyone managed to find a solution to this problem? I still have not managed to successfully calculate and display the average rating and the total amount of ratings on the ‘Ratings Display’ widget.

Regards,
Jayden

Hello all,

I am not working on this project anymore but I thought sharing my code here might help someone. As a reminder my code allows a user to search and rate an item at real-time without using a dataset but instead relying on a repeater and backend code. It took me 3 versions to get where I wanted to be.

Version 1:
import wixData from “wix-data”;

export function searchButton_click(event) {
// Runs a query on the “recipes” collection
wixData.query(“Wines”)
// Query the collection for any items whose “Name” field contains
// the value the user entered in the input element
.contains(“title”, $w(“#searchBox”).value)
.find() // Run the query
.then(res => {
// Set the table data to be the results of the query
$w(“#resultsTable”).rows = res.items;
$w(“#resultsTable”).expand();
console.log(“— button1_click —”);
console.log(res.items);
});
}

$w.onReady( function () {
$w(“#resultsTable”).columns = [{
“id”: “col1”,
“dataPath”: “image”,
“label”: “Image”,
“type”: “image”,
}, {
“id”: “col2”,
“dataPath”: “title”,
“label”: “Title”,
“type”: “string”,
}, {
“id”: “col3”,
“dataPath”: “description”,
“label”: “Description”,
“type”: “string”,
}];
});

Version 2:
import wixData from “wix-data”;
import wixUsers from ‘wix-users’;

export function searchButton_click(event) {
// Runs a query on the “Wines” collection
wixData.query(“Wines”)
// Query the collection for any items whose “title” field contains
// the value the user entered in the input element
.contains(“title”, $w(“#searchBox”).value)
.find() // Run the query
.then(res => {
// Set the table data to be the results of the query
$w(“#resultsTable”).rows = res.items;
$w(“#resultsTable”).expand();
console.log(“— button1_click —”);
console.log(res.items);
});
}

$w.onReady( function () {

//Define resultsTable structure
$w(“#resultsTable”).columns = [{
“id”: “col1”,
“dataPath”: “image”,
“label”: “Image”,
“type”: “image”,
}, {
“id”: “col2”,
“dataPath”: “title”,
“label”: “Title”,
“type”: “string”,
}, {
“id”: “col3”,
“dataPath”: “description”,
“label”: “Description”,
“type”: “string”,
}];

//Get current user
let user = wixUsers.currentUser;

let userId = user.id; // “r5cme-6fem-485j-djre-4844c49”
let isLoggedIn = user.loggedIn; // true

user.getEmail() 
    .then((email) => { 

let userEmail = email; // “user@something.com
console.log(“— onReady 1 —”);
console.log(userEmail);

        wixData.query("Ratings") 
            .contains("email", userEmail) 
            .find() // Run the query 
            .then(ratings => { 
                console.log("--- onReady 2 ---"); 
                console.log(ratings.items); 

let list_id = ratings.items.map(a => a.item);
console.log(“— onReady 3 —”);
console.log(list_id);

                wixData.query("Wines") 
                    .hasSome("_id", list_id) 
                    .find() // Run the query 
                    .then(wines => { 

// Set the table data to be the results of the query
$w(“#resultsTable”).rows = wines.items;
$w(“#resultsTable”).expand();
console.log(“— onReady 4 —”);
console.log(wines.items);
});
});

    }); 

});

Final Version 3:
import wixData from ‘wix-data’;
import wixUsers from ‘wix-users’;

let wines_collection=“Wines2”;
let ratings_collection=“Ratings3”;

$w.onReady( function () {
console.log(“— onReady 1 —”);
wixData.query(wines_collection)
.find()
.then((results) => {
$w(“#repeater”).data = results.items;
});

console.log("--- onReady 2 ---");  
$w("#repeater").onItemReady(($item, itemData, index) => { 
    $item("#image").src = itemData.image; 
    $item("#title").text = itemData.title; 
    $item("#description").text = itemData.region; 

    console.log("--- onReady 3 ---");  

//Get current user
let user = wixUsers.currentUser;
let userId = user.id;
let isLoggedIn = user.loggedIn;
user.getEmail()
.then((email) => {
let userEmail = email;

            wixData.query(ratings_collection) 
                .eq("title", userEmail + "-" + $item("#title").text) 
                .find() 
                .then((ratingsResults) => { 

if (ratingsResults.totalCount > 0) {
let ratingItem = ratingsResults.items[0];
$item(“#rating”).value = ratingItem.rating;
}
})
. catch ((err) => {
let errorMsg = err;
console.log(“— Error wixData.query(Ratings) 1 —”);
console.log(err);
});

        }); 
    console.log("--- onReady 4 ---");       
}); 

});

export function rating_click(event) {
console.log(“— rating_click 1 —”);
let $item = $w.at(event.context);
console.log($item(“#title”).text, $item(“#rating”).value);

//Get current user
let user = wixUsers.currentUser;

let userId = user.id;
let isLoggedIn = user.loggedIn;

console.log(user.getEmail()); 

user.getEmail() 
    .then((email) => { 

let userEmail = email;
console.log(“— rating_click 2 —”);
console.log(userEmail);

        wixData.query(ratings_collection) 

//.eq(“email”, userEmail)
.eq(“title”, userEmail + “-” + $item(“#title”).text)
.find()
.then((results) => {
let item = results.items[0];

//If current user has rated this item before, update its rating based on rating value
if (item) {
console.log(“— rating_click 3 —”);
item.rating = $item(“#rating”).value;
wixData.update(ratings_collection, item);

//If current user has not rated this item before, create a new rating record, using this item’s reference id
} else {
console.log(“— rating_click 4 —”);
let toInsert = {
“title”: userEmail + “-” + $item(“#title”).text,
“email”: userEmail,
“item”: $item(“#title”).text,
“rating”: $item(“#rating”).value
};

                    wixData.insert(ratings_collection, toInsert) 
                                .then((intertedItem) => {}) 
                                . **catch** ((err) => { 

let errorMsg = err;
console.log(“— Error wixData.insert(ratings_collection, toInsert) 1 —”);
console.log(err);
});
console.log(“— rating_click 5 —”);

/*
// Runs a query on the “Wines” collection
wixData.query(wines_collection)
// Query the collection for any items with “title” field equal to the item rated
// the value the user entered in the input element
.eq(“title”, $item(“#title”).text)
.find() // Run the query
.then(wineItems => {
let wineItem = wineItems.items[0];

                            let toInsert = { 
                                "title": userEmail + "-" + $item("#title").text, 
                                "email": userEmail, 
                                "item": wineItem._id, 
                                "rating": $item("#rating").value 
                            }; 

                            wixData.insert(ratings_collection, toInsert) 
                                .then((intertedItem) => {}) 
                                .catch((err) => { 
                                    let errorMsg = err; 
                                    console.log("--- Error wixData.insert(Wines, toInsert) 1 ---"); 
                                    console.log(err); 
                                }); 
                        }); 
                    */  
                } 

            }) 
            . **catch** ((err) => { 

let errorMsg = err;
console.log(“— Error wixData.query(Ratings) 2 —”);
console.log(err);
});
});

}

export function searchButton_click(event) {
console.log(“— searchButton_click 1 —”);
// Runs a query on the “Wines” collection
wixData.query(wines_collection)
// Query the collection for any items whose “title” field contains
// the value the user entered in the input element
.contains(“title”, $w(“#searchBox”).value)
.find() // Run the query
.then(results => {
$w(“#repeater”).data = results.items;
});
}