Chart.js - How to update data - javascript

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);

Related

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 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>

ChartJS: Chart not displaying full range of data

My ChartJS chart is not displaying all the data. This is the closest question on SO to my problem. Implementing the answer to this question did not help (I tried both [{display: false}] and [{display: true}]).
I am a novice at chartjs having only started working with it some ~5 days ago. Any help or advice would be appreciated.
Basically, I am writing a chart that takes data collected by a Raspberry Pi and plots it.
<!DOCTYPE html>
<html lang="en">
<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" />
<title>Harp comfort</title>
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<h1>Temperature data</h1>
<canvas id="myChart"></canvas>
<script>
// Data from: Raspberry Pi Hat
window.addEventListener('load', setup);
var ops = {
scales: {
xAxes: [{
display: false
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
async function setup() {
const ctx = document.getElementById('myChart').getContext('2d');
const dataTemp = await getData();
const myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'Temperature',
data: dataTemp.temp,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.85)',
borderWidth: 2
}
]
},
options: ops
});
}
async function getData() {
const response = await fetch('./sample.csv');
const data = await response.text();
const temp = [];
const rows = data.split('\n').slice(1);
rows.forEach(row => {
const col = row.split(',');
temp.push(parseFloat(col[0]))
//console.log(col[0]) //for debugging purpose
});
return { temp };
}
//getData(); for debugging purpose
</script>
</body>
</html>
The CSV data (sample.csv) is available via this PasteBin page
I am answering my own question.
I was able to solve this problem by ensuring that the CSV data had 2 columns. A single column of data does not work. A two column data file (PasteBin Link) along with the modified code works fine:
<!DOCTYPE html>
<html lang="en">
<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" />
<title>Harp Temperature and RH</title>
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<h1>Harp comfort</h1>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
// Data from: Raspberry Pi Hat
window.addEventListener('load', setup);
var ops = {
scales: {
xAxes: [{
display: false
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
async function setup() {
const ctx = document.getElementById('myChart').getContext('2d');
const dataTemp = await getData();
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: dataTemp.timestamp,
datasets: [
{
label: 'Temperature',
data: dataTemp.temp,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.85)',
borderWidth: 2
}
]
},
options: ops
});
}
async function getData() {
const response = await fetch('./sample.csv');
const data = await response.text();
const timestamp = [];
const temp = [];
const rows = data.split('\n').slice(1);
rows.forEach(row => {
const col = row.split(',');
timestamp.push(col[0])
temp.push(parseFloat(col[1]))
//console.log(col[0]) //for debugging purpose
});
return { temp, timestamp };
}
//getData(); for debugging purpose
</script>
</body>
</html>
I would love it if more refined answers (than my novice solution!) be posted.

Cannot display two Chart.js on one HTML page

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.

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