Chart.js: Count Database Entry and Display on Chart.js.

Hi guys, just a challenge I’m experiencing with displaying number of database entry using Chart.js and I was hoping someone in this forum could help.

So I added a code in my page code to count certain keywords from a database collection and I intend to use the number as the values for a pie chart. Below is the code for the Chart.js HTML component element;

Chart.js HTML Code

<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>

<canvas id="myChart" style="width:200%;max-width:600px"></canvas>

<script>
var xValues = ["Extremely proficient", "Proficient", "Moderately proficient", "Moderately not proficient", "Extremely not proficient"];
  var yValues = [1,2,3,4,5]
  
var barColors = [
  "#4ac0c0",
  "#36a2eb",
  "#ffcc55",
  "#ff9f40",
  "#fe6383"
];

new Chart("myChart", {
  type: "pie",
  data: {
    labels: xValues,
    datasets: [{
      backgroundColor: barColors,
      data: yValues
    }]
  },
  options: {
    title: {
      display: true,
      text: "Previous ECG Knowledge"
    }
  }
});
</script>

</body>
</html>

Page code for counting the database keywords.

wixData.query("Pre-SurveyDatabase")
        .eq('proficiencyLevel', 'Extremely proficient').count().then((num) => {
            var numberOfItems1 = num;
            //console.log(numberOfItems1)
            });
            
     There are more query, for simplicity I will only display one so you can better understand how I did the counting

I’ve tried the postmessage and onMessage APIs but it doesn’t seem to work. Anyone had luck with this?

I appreciate all responses. Thank you greatly!

Try out the Create a Custom Chart example to see how it’s done.

You also might want to consider trying out the Chart.js Custom Element example for a different approach.

Thank you @yisrael-wix I actually went through these examples, but the chart goes blank. So what I also intended was to create an array and post the array to the chart to serve as the yValues. I tried different postmessage and onMessage examples but still doesn’t work. If you could help with a code for that I will greatly appreciate it. Thank you againn