Update the Chartjs push data with ajax - javascript

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

Related

update chart in chart js without reloading the page

i trying to create a chart when users search and it works but the problem when user search again it throw Uncaught Error: Canvas is already in use and when i try to destroy it it throw another error says that destroy is not function, I need a way to make the chart change when user serach without the need to reload the page
my code
var endpoint = "/api/chart/data";
myform.addEventListener("submit", function (e) {
e.preventDefault();
var name = document.querySelector("#name").value;
var amount = document.querySelector("#amount").value;
$.ajax({
method: "GET",
url: endpoint + "?name=" + name + "&amount=" + amount,
success: function (data) {
labels = data.labels;
data = data.data;
console.log("success");
console.log(name);
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels:labels,
datasets: [
{
label: "# of Votes",
data: data,
backgroundColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
],
borderWidth: 1,
borderRadius: 5,
},
],
},
options: {
responsive: true,
scales: {
x: {
min: -100,
max: 100,
ticks: {
color: '#fff',
},
beginAtZero: true,
},
y: {
ticks: {
color: '#fff',
},
beginAtZero: true,
},
},
},
});
},
error:function(){
console.error('enter valid data')
}
});
});
The problem is that the myChart variable is declared inside the scope of the AJAX success function. The variable only exists within the function body during its execution. When the user performs a new search, the success function is invoked again but the initially created myChart variable does no longer exist.
You can solve your problem by creating myChart at the beginning in the global scope as follows.
var myChart = new Chart('myChart', {
type: "bar",
data: {
labels: [], // initialize with an empty array
datasets: [{
label: "# of Votes",
data: [], // initialize with an empty array
...
});
Your event listener and AJAX request would then look as shown below. Note that I set the labels and data on the existing chart and call myChart.update() afterwards. This is cleanest and the most efficient way to deal with new data. For further details, please consult Updating Charts from chart.js documentation.
var endpoint = "/api/chart/data";
myform.addEventListener("submit", function(e) {
e.preventDefault();
var name = document.querySelector("#name").value;
var amount = document.querySelector("#amount").value;
$.ajax({
method: "GET",
url: endpoint + "?name=" + name + "&amount=" + amount,
success: function(data) {
myChart.data.labels = data.labels;
myChart.data.datasets[0].data = data.data;
myChart.update();
},
error: function() {
console.error('enter valid data')
}
});
});

Search box to show information in line chart

I'm trying to add a search box in to my web page that allows the user to select the data to show in a line chart.
I know how to pass the variable from the search box to PHP but the question is how can I render the chart in Javascript to update the information with the value of the search box after I have updated it in the PHP?
$(document).ready(function() {
$.ajax({
url: "http://localhost/chartjs/followersdata.php",
type: "GET",
success: function(data) {
console.log(data);
var userid = [];
var facebook_follower = [];
var twitter_follower = [];
var googleplus_follower = [];
for (var i in data) {
userid.push("UserID " + data[i].userid);
facebook_follower.push(data[i].facebook);
twitter_follower.push(data[i].twitter);
googleplus_follower.push(data[i].googleplus);
}
var chartdata = {
labels: userid,
datasets: [{
label: "facebook",
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: facebook_follower
},
{
label: "twitter",
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: twitter_follower
},
{
label: "googleplus",
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: googleplus_follower
}
]
};
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error: function(data) {}
});
});
Thanks for your replies.
This link can help you
https://www.chartjs.org/docs/latest/developers/api.html
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
LineGraph.render({
duration: 800,
lazy: false,
easing: 'easeOutBounce'
});
I have managed to do this, but I only return the json not the chart rendered.
<form action="./followersdata.php" method="post">
Licencia:<br>
<input type="text" name="licencia" id="licencia"><br>
<input type="submit" value="Submit" onsubmit="return showgraph();">
</form>

Chart.js changing the color of the max value bar

I'm new to JS, I want to create a bar chart where the column with the max value has a different color compared to the others. I can create the chart but I don't manage to access the single column properties. I have been looking for answers on the web but none of the solutions I have found so far helped me. The workflow is the following:
I ask the user for a text input,
Once the user press a button the script calls a function in python (I use python flask) that returns me an array of values and labels,
Then a chart appears on the webpage with these values and labels.
Everything works fine, I'm just not able to change the color of a single bar.
Here is the JS:
$(function() {
$('a#process_input').bind('click', function() {
$.getJSON('/background_process', {
smile: $('input[name="text_string"]').val(),
}, function(data) {
$("#result").text(data.output);
var labels = data.labels;
var values = data.values;
Chart.defaults.global.responsive = false;
var chartData = {
labels : labels,
datasets : [{
label: 'data_label',
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data : values,
scaleShowLabels: true,
spanGaps: false
}]
}
// get chart canvas
var ctx = document.getElementById("myCanvas").getContext("2d");
// create the chart using the chart canvas
var myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scaleShowValues: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
autoSkip: false
}
}]
}
}
});
});
});
});
Here is an example of what I mean:
I think the easiest way to do it is by defining backgroundColor for each bars. Then you can find the max index and change the color. Here is a simplified example:
function argMax(array) {
return array.map((x, i) => [x, i]).reduce((r, a) => (a[0] > r[0] ? a : r))[1];
}
// dummy data
var data = [12, 19, 1, 14, 3, 10, 9];
var labels = data.map((x, i) => i.toString());
// other data color
var color = data.map(x => 'rgba(75,192,192,0.4)');
// change max color
color[argMax(data)] = 'red';
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'value',
data: data,
backgroundColor: color,
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0-beta/Chart.js"></script>
<canvas id="myChart" width="600" height="300"></canvas>
backgroundColor: "rgba(75,192,192,0.4)"
instead of giving it a single color, you can add an array:
backgroundColor:["rgba(255, 99, 132, 0.2)","rgba(255, 159, 64, 0.2)","rgba(255, 205, 86, 0.2)"]
Example:
new Chart(document.getElementById("chartjs-1"), {
"type": "bar",
"data": {
"labels": ["First", "Second", "Third", "Fourth"],
"datasets": [{
"label": "Example Dataset",
"data": [65, 59, 80, 31],
"fill": false,
"backgroundColor": ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 99, 132, 0.2)"],
"borderColor": ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 99, 132)", "rgb(255, 99, 132)"],
"borderWidth": 1
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chartjs-1" class="chartjs">https://stackoverflow.com/posts/51843404/edit#
In the documentation [] denotes which properties accept also arrays (backgroundColor - Color/Color[])

Draw line chart using chart.js with ajax

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

Chart.js line graph change x axis seperation

I am currently creating a system to read data from a mysql database in json format and display this data in a chart.js line graph. The values will be inserted into the database when they are received from the transmitter every minute. The data values in the format are DateTimeOfRecording (mysql DATETIME), Temperature and humidity. I have managed to get the graph to display the data.
However, the graphical seperation between timestamps is the same, no matter what the time difference is between them. Is there any way of scaling them so that, for example, if recording of the data is missed, then a gap will be created in the chart, instead of the next value being placed directly after?
This is my javascript file for creating the chart:
$(document).ready(function(){
$.ajax({
url : "http://"+self.location.host+"/chartjs/tests/ChartDataTest.php",
type : "GET",
success : function(data){
console.log(data);
var Temperature = [];
var RecordingDateTime = [];
var Humidity = [];
for(var i in data)
{
RecordingDateTime.push(data[i].RecordingDateTime);
Temperature.push(data[i].Temperature);
Humidity.push(data[i].Humidity);
}
var chartdata =
{
labels: RecordingDateTime,
datasets:
[
{
label: "Temperature",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(230, 0, 0, 0.75)",
borderColor: "rgba(230, 0, 0, 1)",
pointHoverBackgroundColor: "rgba(230, 0, 0, 1)",
pointHoverBorderColor: "rgba(230, 0, 0, 1)",
data: Temperature
},
{
label: "Humidity",
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: Humidity
}
]
};
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx,
{
type: 'line',
data: chartdata
});
},
error : function(data)
{
}
});
});
I think you need to specify your x-axis as using the type of time.
Try something like this...
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx,
{
type: 'line',
data: chartdata,
options: {
scales: {
xAxes: [
{
type: "time",
time: {
format: timeFormat,
round: 'minute',
}
}],
},
}
});

Categories