First of all, sorry for my english. You need to know I am working on WebDev project and I had just begun using WebDev for my internship. Also, I am not a pro with JS.
There's the problem : I'm trying to add a Chart into a Webdev webpage. I collect the data through a SQL request in the page code. I created a Intern Composant for the container of the chart, and my javascript code is into the Intern Composant code.
When I test it on navigator, the console catches an error as "chart is undefined" and I think this is the real problem here.
Here is the original JS code (found on W3 website) :
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
var yValues = [55, 49, 44, 24, 15];
var barColors = [
"#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"
];
new Chart("myChart", {
type: "doughnut",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues
}]
},
options: {
title: {
display: true,
text: "World Wide Wine Production 2018"
}
}
});
I modified it to delete the data and just created the chart with type and title like this :
function jsInit()
{
new Chart("myChart", {
type: "doughnut",
options: {
title: {
display: true,
text: "World Wide Wine Production 2018"
}
}
});
}
And in another function, I try to add/update the data :
function jsDonnees(sCell, tabDonnées)
{
var chart = document.getElementById("myChart");
var barColors = [
'pink',
'blue',
'red',
'green',
'orange',
'purple'
]
//Add data to chart
for(var i = 0; i < tabDonnées.length; i++){
chart.data.labels.push(tabDonnées[i].Libellé);
chart.data.datasets.forEach((dataset)=> {
dataset.data.push(tabDonnées[i].Utilisations);
dataset.backgroundColor.push(barColors[i]);
});
}
chart.update();
}
I try a lot of things but I confused myself...
I tried the Chart.getChart(id)
method but it didn't work
First, I want to thank you for your answers and comments, kind of help me see clear :)
Most of my problems were typos and lack of attention.
For those who have the same WebDev problem as I do :
I declare let chart;
into the Internal component's control template's global declarations
I create a function jsInit() to create an empty chart :
function jsInit()
{
const ctx = document.getElementById('myChart');
chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [],
datasets: [
{
data: [],
backgroundColor: []
}]
},
options: {
title: {
display: true,
text: "World Wide Wine Production 2018"
}
}
});
}
function jsDonnees(sCell, tabDonnées)
{
var barColors = [
'pink',
'blue',
'red',
'green',
'orange',
'purple'
]
//Ajout des données pour le graphique
for(var i = 0; i < tabDonnées.length; i++){
chart.data.labels.push(tabDonnées[i].Libellé);
chart.data.datasets.forEach((dataset)=> {
dataset.data.push(tabDonnées[i].Utilisations);
dataset.backgroundColor.push(barColors[i]);
});
}
chart.update();
}