Cannot display two Chart.js on one HTML page - javascript

I am trying to display more Chart.js graphics on a single HTML page, but it does not work. I tried several approaches, but none of them had a positive result. I will attach my code:
#extends('layouts.app')
<!DOCTYPE html>
<html lang="zxx">
#section('content')
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/patternomaly#1.3.2/dist/patternomaly.min.js"></script>
#php
$dates = '';
$rates = '';
$graph_data = \App\Helpers\NjHelper::bettingData();
foreach ($graph_data as $item){
$dates .= "'".$item->date."',";
$rates .= $item->bankers.",";
}
#endphp
#php
$datesValue = '';
$ratesValue = '';
$graph_data_value = \App\Helpers\NjHelper::bettingDataValueBets();
foreach ($graph_data_value as $item){
$datesValue .= "'".$item->date."',";
$ratesValue .= $item->value_bet.",";
}
#endphp
<script>
$(function () {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{!! $dates !!}],
datasets: [{
label: 'Bankers Profit Per Day',
data: [{!! $rates !!}],
borderColor: [
'rgba(243, 156, 18, 1)',
'rgba(243, 156, 18, 1)',
'rgba(243, 156, 18, 1)'
],
borderWidth: 3
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
labels: {
fontSize: 20
}
}
}
});
var ctx_2 = document.getElementById(chartValueBets).getContext('2d');
var chartValueBets = new Chart(ctx_2, {
type: 'line',
data: {
labels: [{!! $datesValue !!}],
datasets: [{
label: 'Value Bets Profit Per Day',
data: [{!! $ratesValue !!}],
borderColor: [
'rgba(243, 156, 18, 1)',
'rgba(243, 156, 18, 1)',
'rgba(243, 156, 18, 1)'
],
borderWidth: 3
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
labels: {
fontSize: 20
}
}
}
});
});
</script>
</head>
<div class="col-lg-12 col-xl-4">
<canvas id="myChart" width="400" height="400"></canvas>
<canvas id="chartValueBets" width="400" height="400"></canvas>
</div>
#endsection
</html>
The data that I want to be displayed comes from some SQL queries, this is the reason why I have those two #php sections before the charts.
Only the first chart appears on my HTML page, the one with the name "myChart".
Does anyone know what I could do in order to make the second one appear as well?

On the following line:
var ctx_2 = document.getElementById(chartValueBets).getContext('2d');
You are missing quotation marks around "chartValueBets." If you add quotation marks, it should work properly.

Related

How to use ChartjsPluginStacked100 javascript only, no typescript

good day. Im trying to use the plugin chartjs-plugin-stacked100 with chart.js vs3 but im not having any luck. it stays as normal stacked horizontal bar chart.
I think im doing something wrong when importing or registering i but not know what im doing wrong.
here is how im doing my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-stacked100#1.0.0"></script>
</head>
<body>
<div id="my-chart-container" style="height:400px;">
<canvas id="my-chart" ></canvas>
</div>
<script src="./index.js" type="module"></script>
</body>
</html>
and here is how im doing my js:
Chart.register(ChartjsPluginStacked100);
new Chart(document.getElementById("my-chart"), {
type: "bar",
data: {
labels: ["2010-2015", "2016", "2017", "2018", "2019"],
datasets: [
{ label: "IG", data: [0, 250, 7417.5, 650, 1455], backgroundColor: "rgba(244, 143, 177, 0.6)" },
{ label: "HY", data: [0, 0, 0, 1000, 0], backgroundColor: "rgba(255, 235, 59, 0.6)" },
{ label: "NR", data: [0, 675, 4182.5, 1505, 1735], backgroundColor: "rgba(100, 181, 246, 0.6)" }
]
},
options: {
indexAxis: 'y',
scales: {
xAxis:{
stacked:true
},
yAxis:{
stacked:true
},
},
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
const datasetIndex = tooltipItem.datasetIndex;
const datasetLabel = data.datasets[datasetIndex].label;
// You can use two type values.
// `data.originalData` is raw values,
// `data.calculatedData` is percentage values, e.g. 20.5 (The total value is 100.0)
const originalValue = data.originalData[datasetIndex][tooltipItem.index];
const rateValue = data.calculatedData[datasetIndex][tooltipItem.index];
return `${datasetLabel}: ${rateValue}% (raw ${originalValue})`;
}
}
},
plugins: {
plugins:[ChartDataLabels],
stacked100: { enable: true, replaceTooltipLabel: false }
}
}
});
if anyone can guide me to do it correctly would be appreciated.
here is a jsbin with it, example
Thanks for your time.

How to hide the legend display for a specific chart?

What I'm trying now is if I have 1 chart and then, when I click on a button with the "onchange" function, it'll display several chart. But when I'm clicking back, I have the chart I want but there is still the "legend" of the 2nd chart in the top of the 1st chart.
Is there a way to remove it ? I've found options: { legend: { display: false } but it remove the legend for all the chart.
Here is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div class="row mt-3">
<div class="col-md-12">
<div style="width:75%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
<label class="form-check-label" for="checkBox">Catégories</label>
</div>
</div>
</div>
<script>
var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];
var test3 = [90, 10, 90, 10, 50, 40, 23, 62, 13, 32, 11, 13];
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
datasets: [{
label: 'My test1',
fill : false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {fill : false
}]
},
// Configuration options go here
options: {}
});
function toggleCategories(e){
if (e.target.checked) {
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
chart.data.datasets[0].label = 'My test1';
chart.data.datasets[0].data = test1;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = '';
chart.data.datasets[1].data = '';
chart.data.datasets[1].borderColor = '';
}
chart.update();
}
</script>
</body>
</html>
Cordially
Chart.js highly depends on its data. Therefore, the easiest way is just dynamically populating the necessary data to your chart whenever you need it. This should add and remove the legend as expected. However, don't forget updating your chart on data change.
Let's add some code to get an idea about it, since basically you're actually doing it - but just a little bit wrong.
The data of your chart is stored in dataset. As we can see you have 2 entries whereas the 2nd one is just an object containing a boolean property (fill). Therefore, it's displaying undefined in your legend at the very beginning.
datasets: [{
label: 'My test1',
fill: false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {
fill: false
}]
However, when toggling the the checkbox it looks fine, since you're overwriting everything within your toggleCategories as seen below.
function toggleCategories(e) {
if (e.target.checked) {
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
...
}
chart.update();
}
But taking a closer look to else shows what's going on here.
// Those 3 lines just reset on index 1, it doesn't get deleted
chart.data.datasets[1].label = '';
chart.data.datasets[1].data = '';
chart.data.datasets[1].borderColor = '';
So in order to get rid of the 2nd legend when you only want 1, you simply have to remove the object of dataset[1] and re-add it whenever you need it.
You might want to look into this fiddle for a fully working example:
It could be a solution?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div class="row mt-3">
<div class="col-md-12">
<div>
<h5 id="legend" style="text-align: center;">My test 1</h5>
</div>
<div style="width:75%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
<label class="form-check-label" for="checkBox">Catégories</label>
</div>
</div>
</div>
<script>
var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];
var test3 = [90, 10, 90, 10, 50, 40, 23, 62, 13, 32, 11, 13];
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
datasets: [{
label: 'My test1',
fill : false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {fill : false
}]
},
// Configuration options go here
options: {legend:{display: false}}
});
function toggleCategories(e){
if (e.target.checked) {
changeLegendOnCl();
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
document.getElementById("legend").innerHTML = "My test 1";
chart.data.datasets[0].label = 'My test1';
chart.data.datasets[0].data = test1;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test1';
chart.data.datasets[1].data = test1;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
}
chart.update();
}
function changeLegendOnCl(){
document.getElementById("legend").innerHTML = "My test 2"+" "+"My test 3";
}
</script>
</body>
</html>

Chart.js - How to update data

I've created chart that shows temperature from past 20 minute. Data is obtained via GET request from my Thingspeak meteo station. How could I send new request every 10 seconds and update only data in chart.
I think chart.update() would work, but I have no idea how to implement it :/
Here is some code:
chartIt();
async function chartIt(){
const loadedData = await loadData();
var myChart = new Chart(document.getElementById("tempChart").getContext('2d'), {
type: 'line',
backgroundColor: 'rgba(255, 251, 230, 0.5)',
data: {
labels: loadedData.timeStamp,
datasets: [{
label: 'Temperature',
data: loadedData.chartData,
backgroundColor: [
'rgba(255, 0, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
})
}
async function loadData() {
var chartData = [];
var timeStamp = [];
await $.getJSON('https://api.thingspeak.com/channels/214058/fields/1.json?minutes=20', function(data) {
$.each(data.feeds, function(){
var value = this.field1;
var raw_time = this.created_at;
if (value) {
value = (value / 1000) * 1000;
value = parseFloat(value.toFixed(2));
}
if (raw_time){
var timewZ = raw_time.split("T").slice(1);
}
chartData.push(value);
timeStamp.push(timewZ);
});
});
return {chartData, timeStamp};
}
.chartWrapper{
width: 500px;
height: 500px;
margin:auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="chartWrapper">
<canvas id="tempChart"></canvas>
</div>
</body>
<script src="script.js"></script>
</html>
This is simplistic but would do the trick. If you wanted to enable/disable it, you'd want to hang onto your interval so you can kill it... This works though! :)
const updateFreqency = 10000;
chartIt(updateFreqency);
async function chartIt(interval){
const loadedData = await loadData();
var myChart = new Chart(document.getElementById("tempChart").getContext('2d'), {
type: 'line',
backgroundColor: 'rgba(255, 251, 230, 0.5)',
data: {
labels: loadedData.timeStamp,
datasets: [{
label: 'Temperature',
data: loadedData.chartData,
backgroundColor: [
'rgba(255, 0, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
})
setInterval(async () => {
const data = await loadData();
myChart.data.datasets.forEach(d => d.data = data.chartData)
myChart.labels = data.timeStamp
myChart.update()
}, interval)
}
async function loadData() {
var chartData = [];
var timeStamp = [];
await $.getJSON('https://api.thingspeak.com/channels/214058/fields/1.json?minutes=20', function(data) {
$.each(data.feeds, function(){
var value = this.field1;
var raw_time = this.created_at;
if (value) {
value = (value / 1000) * 1000;
value = parseFloat(value.toFixed(2));
}
if (raw_time){
var timewZ = raw_time.split("T").slice(1);
}
chartData.push(value);
timeStamp.push(timewZ);
});
});
return {chartData, timeStamp};
}
.chartWrapper{
width: 500px;
height: 500px;
margin:auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="chartWrapper">
<canvas id="tempChart"></canvas>
</div>
</body>
<script src="script.js"></script>
</html>
basically you need access to chart so if you move its context/scope to be outside of the function then you can access it from another function....
something like....
ommited some of the code as well this is the core bits..
//moved out
var myChart;
async function chartIt(){
const loadedData = await loadData();
myChart = new Chart(document.getElementById("tempChart").getContext('2d'), {
type: 'line',
backgroundColor: 'rgba(255, 251, 230, 0.5)',
data: {
labels: loadedData.timeStamp,
datasets: [{
label: 'Temperature',
data: loadedData.chartData,
backgroundColor: [
'rgba(255, 0, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
})
}
function myTimer() {
var loadedData = await loadData();
//have access here as it was move out of the function which created it.
myChart.data.labels = loadedData.timeStamp;
myChart.data.datasets = loadedData.chartData;
myChart.update();
}
var myVar = setInterval(myTimer, 10000);

Chart.js chart not displaying until I open the browser's console

I was trying to create a simple chart that displays covid-19 data with chart.js, but for some reason the code I wrote up was not working. The chart is empty upon loading the page, but if I open up the browser's console, the data suddenly shows up. And if I load the page with the console open, the chart is still empty, but if I close the console, the chart is filled.
Here is what it looks like upon loading the page with the console open: empty chart
And here is what it looks like immediately after I close the console: filled chart
The following is all the code I used:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Playing with Covid19 data</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.0/css/bulma.min.css">
</head>
<body>
<canvas id="deathChart" width="100" height="50"></canvas>
<script>
const api_url = "https://covidtracking.com/api/us/daily"
let dates = [],
deaths =[],
hospitalizations = [],
negatives = [],
positives = [],
recoveries = [],
onVentilatorCurrently_list = []
function getData()
{
console.log("About to fetch the data")
fetch(api_url)
.then(response => response.json())
.then(data => {
for(let row of data){
let {date, death, hospitalized, negative, onVentilatorCurrently, positive, recovered} = row
dates.splice(0, 0, date)
deaths.splice(0, 0, death)
hospitalizations.splice(0, 0, hospitalized)
negatives.splice(0, 0, negative)
onVentilatorCurrently_list.splice(0, 0, onVentilatorCurrently)
positives.splice(0, 0, positive)
recoveries.splice(0, 0, recovered)
}
console.log("Finished fetching the data")
})
}
getData()
let death_config = {
type: 'line',
data:
{
labels: dates,
datasets: [
{
label: "Deaths from Covid-19",
data: deaths,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderWidth: 1
}
]
},
options: {
tooltips: {
mode: "index",
intersect: false,
},
}
}
let death_ctx = document.getElementById('deathChart').getContext('2d')
let deathChart = new Chart(death_ctx, death_config)
</script>
</body>
So I think you are loading the data before the chart is finished rendering. When you open/close the console it is resizing the window which triggers a re-render and shows the data properly. You can fix this by creating the chart after the data is done loading.
Edit: Changed to call chart.update() per OP's request.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Playing with Covid19 data</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.0/css/bulma.min.css">
</head>
<body>
<canvas id="deathChart" width="100" height="50"></canvas>
<script>
const api_url = "https://covidtracking.com/api/us/daily"
let dates = [],
deaths = [],
hospitalizations = [],
negatives = [],
positives = [],
recoveries = [],
onVentilatorCurrently_list = []
function getData(chart) {
console.log("About to fetch the data")
fetch(api_url)
.then(response => response.json())
.then(data => {
for (let row of data) {
let {
date,
death,
hospitalized,
negative,
onVentilatorCurrently,
positive,
recovered
} = row
dates.splice(0, 0, date)
deaths.splice(0, 0, death)
hospitalizations.splice(0, 0, hospitalized)
negatives.splice(0, 0, negative)
onVentilatorCurrently_list.splice(0, 0, onVentilatorCurrently)
positives.splice(0, 0, positive)
recoveries.splice(0, 0, recovered)
}
console.log("Finished fetching the data")
chart.update();
})
}
let death_config = {
type: 'line',
data: {
labels: dates,
datasets: [{
label: "Deaths from Covid-19",
data: deaths,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderWidth: 1
}]
},
options: {
tooltips: {
mode: "index",
intersect: false,
},
}
}
let death_ctx = document.getElementById('deathChart').getContext('2d')
let deathChart = new Chart(death_ctx, death_config)
getData(deathChart);
</script>
</body>
Check
const api_url = "https://covidtracking.com/api/us/daily";
let dates = [],
deaths =[],
hospitalizations = [],
negatives = [],
positives = [],
recoveries = [],
onVentilatorCurrently_list = []
function getData(){
console.log("About to fetch the data")
fetch(api_url)
.then(response => response.json())
.then(data => {
for(let row of data){
let {date, death, hospitalized, negative, onVentilatorCurrently, positive, recovered} = row
dates.splice(0, 0, date)
deaths.splice(0, 0, death)
hospitalizations.splice(0, 0, hospitalized)
negatives.splice(0, 0, negative)
onVentilatorCurrently_list.splice(0, 0, onVentilatorCurrently)
positives.splice(0, 0, positive)
recoveries.splice(0, 0, recovered)
}
console.log("Finished fetching the data")
})
}
getData()
let death_config = {
type: 'line',
data:
{
labels: dates,
datasets: [
{
label: "Deaths from Covid-19",
data: deaths,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderWidth: 1
}
]
},
options: {
tooltips: {
mode: "index",
intersect: false,
responsive: true,
maintainAspectRatio: true
},
}
}
let death_ctx = document.getElementById('deathChart').getContext('2d')
let deathChart = new Chart(death_ctx, death_config)
setTimeout(function() { deathChart.update(); },1000);
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.0/css/bulma.min.css">
<div><canvas id="deathChart" width="100" height="50"></canvas></div>

Pie chart with Chart.js and mySQL

I'm trying to display a pie chart using the result of some queries. But nothing is showing. I don't know where the mistake is in my javascript:
$(document).ready(function(){
$.ajax({
url:"http://localhost/bigdata/data.php",
method:"GET",
success:function(data) {
console.log(data);
var male =[];
var female =[];
male.push("male: "+data[0].maleid);
female.push("female: "+data[1].femaleid);
var data1 = {
labels: [
"Male",
"Female"
],
datasets: [
{
data: [male,female],
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
]
}]
};
var ctx =$("#mycanvas");
var myPieChart = new Chart(ctx,{
type: 'doughnut',
data: data1,
options: {
animation:{
animateScale:true,
responsive: true,
maintainAspectRatio: true
}
}
});
},
error:function(data){
console.log(data);
}
});
});
<!-- end snippet--!>
Besides , my php code of query execution works also my html page .
<!-- begin snippet: js hide: false console: true babel: false -->
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8"/>
<title>Chart</title>
<style type="text/css">
#chart-container{
width:640px;
height:auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<script src="Chart.js"></script>
<script src="jquery-3.2.1.js"></script>
<script src="app.js"></script>
</body>
</html>
<?php
header('Content-Type:application\json');
define('DB_HOST','127.0.0.1');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME','gestionpersdb');
$mysqli=new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
if(!$mysqli)
{
die("connection failed:".$myqli->error);
}
$male="SELECT * FROM gestiondb_users WHERE gender='male'";
$result_male=$mysqli->query($male);
$num_males=mysqli_num_rows($result_male);
$female="SELECT * FROM gestiondb_users WHERE gender='female'";
$result_female=$mysqli->query($female);
$num_females=mysqli_num_rows($result_female);
$data=array();
$data[0]=$num_males;
$data[1]=$num_females;
$result_male->close();
$result_female->close();
$mysqli->close();
print json_encode($data);
?>
In case you're still trying to get it to work, here is how I did it:
<script type="text/javascript">
$.ajax({
url:"getdata.php",
method:"GET",
success:function(data) {
console.log(data);
var malenum =[1];
var femalenum =[2];
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Male","Female"],
datasets: [{
label: 'Genders',
data: [malenum,femalenum],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
});
},
error:function(data){
console.log(data);
}
});
</script>

Categories