Related
I'm trying to get the ChartJS line chart working for a project I am working on. I followed a tutorial as I need to get the data from mySQL database and use this data to be displayed on the line chart.
I was wondering if anyone had experience using ChartJS and could tell me what's wrong with my code, please.
I have removed the weblink to the JSON data just for privacy reasons, but the data is shown in JSON format.
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - LineGraph</title>
<style>
.chart-container {
width: 640px;
height: auto;
}
</style>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/linegraph.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
</head>
<body>
<div class="chart-container">
<canvas id="mycanvas" width="600" height="600"></canvas>
<script>
$(document).ready(function(){
$.ajax({
url : "**********",
type : "GET",
success : function(data){
console.log(data);
var user_id = [];
var pain = [];
var sleep = [];
var mood = [];
var heartrate = [];
var time_of_entry = [];
for(var i in data) {
user_id.push("UserID " + data[i].user_id);
pain.push(data[i].pain);
sleep.push(data[i].sleep);
mood.push(data[i].mood);
heartrate.push(data[i].heartrate);
time_of_entry.push(data[i].timeofentry);
}
var chartdata = {
labels: user_id,
datasets: [
{
label: "pain",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(59, 89, 152, 0.75)",
borderColor: "rgba(59, 89, 152, 1)",
pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
pointHoverBorderColor: "rgba(59, 89, 152, 1)",
data: pain
},
{
label: "sleep",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(29, 202, 255, 0.75)",
borderColor: "rgba(29, 202, 255, 1)",
pointHoverBackgroundColor: "rgba(29, 202, 255, 1)",
pointHoverBorderColor: "rgba(29, 202, 255, 1)",
data: sleep
},
{
label: "mood",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(211, 72, 54, 0.75)",
borderColor: "rgba(211, 72, 54, 1)",
pointHoverBackgroundColor: "rgba(211, 72, 54, 1)",
pointHoverBorderColor: "rgba(211, 72, 54, 1)",
data: mood
},
{
label: "heartrate",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(211, 72, 54, 0.75)",
borderColor: "rgba(211, 72, 54, 1)",
pointHoverBackgroundColor: "rgba(211, 72, 54, 1)",
pointHoverBorderColor: "rgba(211, 72, 54, 1)",
data: heartrate
},
{
label: "time_of_entry",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(211, 72, 54, 0.75)",
borderColor: "rgba(211, 72, 54, 1)",
pointHoverBackgroundColor: "rgba(211, 72, 54, 1)",
pointHoverBorderColor: "rgba(211, 72, 54, 1)",
data: time_of_entry
}
]
};
var ctx = $("#mycanvas");
var mycanvas = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error : function(data) {
}
});
});
</script>
</div>
</body>
Step 1 - json data is wrong use The JSON Validator to check.
Here is the correct json data.
[{"0":"1","user_id":"1","1":"3","pain":"3","2":"3","sleep":"3","3":"3","mood":"3","4":"32","heartrate":"32","5":"2019-06-20 09:52:43","time_of_entry":"2019-06-20 09:52:43"},{"0":"1","user_id":"1","1":"3","pain":"3","2":"3","sleep":"3","3":"3","mood":"3","4":"32","heartrate":"32","5":"2019-06-20 09:52:53","time_of_entry":"2019-06-20 09:52:53"},{"0":"1","user_id":"1","1":"2","pain":"2","2":"23","sleep":"23","3":"3","mood":"3","4":"89","heartrate":"89","5":"2019-06-20 09:53:20","time_of_entry":"2019-06-20 09:53:20"}]
Step 2- parse the json data then use. It will work.
Attached the screenshot.
https://www.screencast.com/t/6t4r6hqMTw
$(document).ready(function(){
$.ajax({
url : "**********",
type : "GET",
success : function(data){
data = jQuery.parseJSON( data);
-------
I'm tring to get Line Chart using Chart.js with ajax json data.
Basically It is ok using custom data eg. [176,617,930,606,649,0,0,0].
But I can't able to get the chart with ajax json data if I try like the below.
My JSON Data is
{'pvideo':[ {'DDATE':"2017-01","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-01","TOCDDB_VALUE":"CRREQUEST","CNT":"176"}, {'DDATE':"2017-01","TOCDDB_VALUE":"NOCR","CNT":"0"}, {'DDATE':"2017-02","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-02","TOCDDB_VALUE":"CRREQUEST","CNT":"617"}, {'DDATE':"2017-02","TOCDDB_VALUE":"NOCR","CNT":"0"}, {'DDATE':"2017-03","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-03","TOCDDB_VALUE":"CRREQUEST","CNT":"930"}, {'DDATE':"2017-03","TOCDDB_VALUE":"NOCR","CNT":"0"}, {'DDATE':"2017-01","TOCDDB_VALUE":"SREG","CNT":"247"}, {'DDATE':"2017-02","TOCDDB_VALUE":"SREG","CNT":"94"}, {'DDATE':"2017-03","TOCDDB_VALUE":"SREG","CNT":"76"} ], ptrights:[ {'DDATE':"2017-01","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-01","TOCDDB_VALUE":"CRREQUEST","CNT":"27"}, {'DDATE':"2017-01","TOCDDB_VALUE":"NOCR","CNT":"10"}, {'DDATE':"2017-02","TOCDDB_VALUE":"DENY","CNT":"3"}, {'DDATE':"2017-02","TOCDDB_VALUE":"CRREQUEST","CNT":"10"}, {'DDATE':"2017-02","TOCDDB_VALUE":"NOCR","CNT":"23"}, {'DDATE':"2017-03","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-03","TOCDDB_VALUE":"CRREQUEST","CNT":"32"}, {'DDATE':"2017-03","TOCDDB_VALUE":"NOCR","CNT":"11"}]}
And code is
var crcnt = [];
var crcnt2 = [176,617,930,606,649,0,0,0];
var nocrcnt = [];
var denycnt = [];
$.getJSON(url, function(data) {
// I use lodash.js for _.filter and ._map
var crlist = _.filter(data.pvideo, function(o) { return o.TOCDDB_VALUE == 'CRREQUEST' });
var nocrlist = _.filter(data.pvideo, function(o) { return o.TOCDDB_VALUE == 'NOCR' });
var denylist = _.filter(data.pvideo, function(o) { return o.TOCDDB_VALUE == 'DENY' });
var crcnt = _.map(crlist, "CNT");
var nocrcnt = _.map(nocrlist, "CNT");
var denycnt = _.map(denylist, "CNT");});
var canvas1 = new chart(doucment.getElementByID("canvas1"), {
type: 'line',
data: {
labels: ["Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug"],
datasets: [{
label: "CRREQUEST",
backgroundColor: "rgba(255, 99, 00, 0.31)",
borderColor: "rgba(255, 99, 204, 0.7)",
pointBorderColor: "rgba(255, 99, 99, 0.7)",
pointBackgroundColor: "rgba(255, 33, 99, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
data: crcnt
}, {
label: "NOCR",
backgroundColor: "rgba(204, 255, 255, 0.70)",
borderColor: "rgba(99, 255, 255, 0.70)",
pointBorderColor: "rgba(3, 88, 106, 0.70)",
pointBackgroundColor: "rgba(0, 33, 255, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: nocrcnt
}, {
label: "DENY",
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(0,0,30,1)",
pointBorderColor: "rgba(3, 88, 106, 0.70)",
pointBackgroundColor: "rgba(3, 88, 106, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: denycnt
}]});
I checked that custom data and json data is same by chrome console.
Console Capture
I'm new in Chart JS and I'm trying to add the maximum values for each dataset inside the legend. I've tried using legendCallback :
HTML:
<canvas id="lineChart"></canvas>
Javascript:
var ctx = document.getElementById("lineChart");
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['1','2','3','4','5','6','7','8','9','10'],
datasets: [{
label: "Max",
backgroundColor: "rgba(235, 70, 70, 0.31)",
borderColor: "rgba(231, 25, 25, 0.7)",
pointBorderColor: "rgba(231, 25, 25, 0.7)",
pointBackgroundColor: "rgba(231, 25, 25, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointBorderWidth: 1,
data: [31, 74, 6, 39, 20, 85, 7, 80, 35, 70]
}, {
label: "Avg",
backgroundColor: "rgba(255, 255, 111, 0.3)",
borderColor: "rgba(255, 255, 50, 0.70)",
pointBorderColor: "rgba(255, 255, 50, 0.70)",
pointBackgroundColor: "rgba(255, 255, 50, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: [82, 23, 66, 9, 99, 4, 2, 25, 67, 20]
},
{
label: "Min",
backgroundColor: "rgba(90, 189, 90, 0.3)",
borderColor: "rgba(50, 173, 50, 0.70)",
pointBorderColor: "rgba(50, 173, 50, 0.70)",
pointBackgroundColor: "rgba(50, 173, 50, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: [30, 46, 60, 29, 79, 54, 23, 25, 47, 10]
}]
},
options: {
legend: {
display: true,
position: 'bottom'
},
legendCallback: function(chart) {
return 'a';
},
scales: {
xAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
});
but the displayed legend didn't changed. I've searched for some answers and I also tried using: lineChart.generateLegend(); but still no result.
It is possible to add the maximum value for each dataset inside legend?
Thanks in advance!
Yes, it is possible to show the max value for each dataset inside the legend. You can use the legend.labels.generateLabels config property to do this.
This property allows you to define your own function that generates the legend labels. To add the max, we simply iterate through each dataset's data array, find the max, and build it into the label string.
Here is an example configuration. The magic happens when we set the text property in the return.
legend: {
display: true,
position: 'bottom',
labels: {
generateLabels: function(chart) {
var data = chart.data;
return Chart.helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
return {
text: dataset.label + " (Max Value: " + Chart.helpers.max(dataset.data).toLocaleString() + ")",
fillStyle: (!Chart.helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
hidden: !chart.isDatasetVisible(i),
lineCap: dataset.borderCapStyle,
lineDash: dataset.borderDash,
lineDashOffset: dataset.borderDashOffset,
lineJoin: dataset.borderJoinStyle,
lineWidth: dataset.borderWidth,
strokeStyle: dataset.borderColor,
pointStyle: dataset.pointStyle,
// Below is extra data used for toggling the datasets
datasetIndex: i
};
}, this) : [];
},
},
},
I also created a codepen to demonstrate this.
This is the code that I have created to render chart with Chart.js library:
$(document).ready(function(){
$.ajax({
url : "data.php",
type : "JSON",
success : function(data){
var lung = data.length;
console.log(data);
var timestamp_utc = [];
var temperature = [];
for(var i in data) {
timestamp_utc.push(data[i].timestamp_utc);
temperature.push(data[i].temperature);
}
var config_temp = {
labels: timestamp_utc.slice(lung-10, lung),
datasets: [
{
label: "temperature",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(0, 169, 252, 0.75)",
borderColor: "rgba(0, 169, 252, 1)",
pointRadius: "5",
pointColor: "rgba(0, 169, 252, 1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "rgba(0, 169, 252, 1)",
pointHoverBorderColor: "rgba(0, 169, 252, 1)",
data: temperature.slice(lung-10, lung)
}]
};
var ctx_temp = $("#mycanvas");
var LineGraph_temp = new Chart(ctx_temp, {
type: 'line',
data: config_temp
});
},
error : function(data) {
}
});
});
I want to update graph every 15 minutes.
how can I do that?
You can use setInterval method to execute the code which renders the chart with updated data.
var pollInterval = 15000; //change this value as needed
function renderChart() {
// put your existing code to render the chart here
}
$(function () {
window.setInterval(renderChart, pollInterval);
});
When my B laptop connect to the A laptop through xampp, I can see all the data but the only thing that i cannot see is the graph. The page will display but only the graph is missing. Why is it like that?
The js that I use is Chart.min.js and jquery-3.1.1.min.js
//This is my js
$(document).ready(function(){
$.ajax({
url : "http://localhost/HerbalifePortal/data2.php",
type : "GET",
success : function(data){
console.log(data);
var feedback_date = [];
var weight = [];
var height = [];
var bmi = [];
var visceral = [];
var water = [];
var body_fat = [];
for(var i in data) {
feedback_date.push("Date " + data[i].feedback_date);
weight.push(data[i].weight);
height.push(data[i].height);
bmi.push(data[i].bmi);
visceral.push(data[i].visceral);
water.push(data[i].water);
body_fat.push(data[i].body_fat);
}
var chartdata = {
labels: feedback_date,
datasets: [
{
label: "Weight(KG)",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(59, 89, 152, 0.75)",
borderColor: "rgba(59, 89, 152, 1)",
pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
pointHoverBorderColor: "rgba(59, 89, 152, 1)",
data: weight
},
{
label: "Height(cm)",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(29, 202, 255, 0.75)",
borderColor: "rgba(29, 202, 255, 1)",
pointHoverBackgroundColor: "rgba(29, 202, 255, 1)",
pointHoverBorderColor: "rgba(29, 202, 255, 1)",
data: height
},
{
label: "BMI",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(29, 289, 152, 0.75)",
borderColor: "rgba(29, 289, 152, 1)",
pointHoverBackgroundColor: "rgba(29, 289, 152, 1)",
pointHoverBorderColor: "rgba(29, 289, 152, 1)",
data: bmi
},
{
label: "Visceral fat level (%)",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(15, 300, 50, 0.75)",
borderColor: "rgba(15, 300, 50, 1)",
pointHoverBackgroundColor: "rgba(15, 300, 50, 1)",
pointHoverBorderColor: "rgba(15, 300, 50, 1)",
data: visceral
},
{
label: "Body water percentage (%)",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(150, 100, 100, 0.75)",
borderColor: "rgba(150, 100, 100, 1)",
pointHoverBackgroundColor: "rgba(150, 100, 100, 1)",
pointHoverBorderColor: "rgba(150, 100, 100, 1)",
data: water
},
{
label: "Body fat (%)",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(200, 50, 0, 0.75)",
borderColor: "rgba(200, 50, 0, 1)",
pointHoverBackgroundColor: "rgba(200, 0, 50, 1)",
pointHoverBorderColor: "rgba(200, 50, 0, 1)",
data: body_fat
},
]
};
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error : function(data) {
}
});
});
//This is where the graph will display
<?php
session_name ('YourVisitID');
session_start();
include ('./header3.html');
?>
<section id="main" class="wrapper">
<div class="container">
<link rel="stylesheet" href="css/bootstrap.css" />
<?php
echo "<h1>{$_SESSION['last_name']} Feedback Information</h1>
<p><br /><br /></p>";
echo'<p><br>Change to table</br></p>';
?>
<div class="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/linegraph.js"></script>
</div>
</section>
<?php
include ('./footer.html');
?>
//This is the place where i get the data and put in the js
<?php
session_name ('YourVisitID');
session_start();
//setting header to json
header('Content-Type: application/json');
$last_name = $_SESSION['last_name'];
//database
define('DB_HOST', 'localhost');
define('DB_FEEDBACK', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'herbalife');
//get connection
$mysqli = new mysqli(DB_HOST, DB_FEEDBACK, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = "SELECT weight, height, water, visceral, body_fat, bmi, feedback_date, feedback_id
FROM feedback, coach, customer
WHERE feedback.customer_id = customer.customer_id AND customer.coach_id = coach.coach_id AND coach.coach_id = {$_SESSION['coach_id']} AND customer.customer_lastname = '$last_name'
ORDER BY feedback_date";
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
This is what i can see from my own laptop