How does one add data to a Chart in an ajax call? - javascript

I am trying to add data obtained from an ajax call to a chart using Chart.js.
The following code is not working:
$(document)
.ready(function () {
fetchBeds($("#site").val());
var ctx = $('#paretoChart');
var paretoChart = new Chart(ctx);
fetchChartData(1, '2016-10-28', '2016-11-2', paretoChart);
});
function fetchChartData(bed, start, end, chart) {
$.ajax({
url: "/reports/fetchChartData",
type: "GET",
data: {
bed: bed,
start: start,
end: end
},
dataType: "json",
success: function (response) {
var chartData = {
labels: response.data.labels,
datasets: [{
label: 'Pareto of Events',
data: response.data.chartData,
}]
};
chart.data = chartData;
console.log(chart);
chart.update();
}
});
}
When run, it doesn't generate any errors (my ajax call is working fine, verified in firefox). Simply nothing happens. I have a feeling it has to do with how I am applying the data to the chart. If I take the example data from the chart.js website and use that directly in the new Chart(...) call, it works fine.
Is it even possible to apply new data after the chart has been created?
Here is the data returned from the ajax call, just in case:
{"result":true,"message":null,"data":{"labels":["Plant","Process"],"chartData":["1","1"]}}
Thank you!

Alright I got the newest ChartJS and tried it out with your scenario.
My html:
<canvas id="myChart" width="200" height="200"></canvas>
Creating the chart:
$(function () {
var ctx = $("#myChart");
var myChart = new Chart(ctx, { type: 'bar', data: { labels: [], datasets: [] } });
UpdateChart(myChart)
});
I had to specify the type and a data object with empty labels and datasets for it to even render on the screen as an empty chart.
My function that updates the chart:
function UpdateChart(chart) {
var data = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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
}]
}
chart.data.labels = data.labels
chart.data.datasets = data.datasets
chart.update()
}
I tried doing chart.data = data but that didn't work for me. I had to specifically update data.labels then data.datasets before updating.

Worked fine by me, see my exact code below.
You have to make sure that you are using the updated .js file of the chart.js plugin. Of course, you have to include Jquery plugin on top of your every javascript file.
For this replication, I used the cdn provided by jquery and chart.js.
<canvas id="chart" height="400px" width="400px"></canvas>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.js"> </script>
<script>
$.ajax({
url: "http://localhost:8081/chart.php",
dataType: "json",
success: function(response)
{
var ctx = document.getElementById("chart");
var myBarChart = new Chart(ctx, {
type: 'pie',
data: {
labels: response.data.labels,
datasets: [{
label: 'Number of Active Customers',
data: response.data.chartData,
backgroundColor: [
'rgba(75, 192, 192, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(75, 192, 192, 1)',
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
}
});
}
});
</script>
chart.php file contains only the response JSON code as you may see below.
{
"result":true,
"message":null,
"data":{
"labels":[
"Plant",
"Process"
],
"chartData":[
"10",
"1"
]
}
}

Related

Update Chart using ChartJS - VueJS

so I'm having some problems when trying to update a chart using VueJS and ChartJS. I'm currently running a ajax request (using axios) and trying to draw a chart from the data returned.
The problem is when trying to draw the chart I get the following error: TypeError: Cannot read property 'getContext' of undefined at eval (App.vue?26cd:520). I don't really know why this is happening, I've read some other posts but still can't seem to get it working. This is the code I'm using:
<template>
<button #click="myFunction()">Click Me</button>
<canvas ref="myChart"></canvas>
</template>
-----------------------------------------------------------
methods: {
myFunction () {
var self = this
axios.post('http://localhost/link/to/file.php', {
// Post params here
}).then(response => {
var ctxChart = self.$refs.myChart.getContext('2d')
var myChart = new Chart(ctxChart, {
type: 'pie',
data: {
labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4'],
datasets: [{
label: 'Label here',
data: [response.data['data1'], response.data['data2'], response.data['data3'], response.data['data4']],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
],
borderWidth: 1
}]
},
options: {
}
})
}).catch(e => {
console.log(e)
})
}
}
Any help is greatly appreciated! :)
I had similar problem. I solved it by wrapping everything with nextTick
self.$nextTick(() => {
var ctxChart = self.$refs.myChart.getContext('2d')
...
});

Chart.js passing value data dynamic

I am want to use data and level dynamic by ajax, so i am using as below but not working.
My ajax return data in json_encode of php.
My code is:
success: function (result) {
result = JSON.parse(result);
var labels = result['labels'];
var data = result['data'];
//console.log(data);
var ctx = document.getElementById("chartbtc");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [labels],
datasets: [{
label: 'Market Price (USD)',
data: [data],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
}
}
});
}
But chart is not generating:
Ajax result is:
{"labels":"13-Nov-2017, 14-Nov-2017, 15-Nov-2017, 16-Nov-2017, 17-Nov-2017, 18-Nov-2017, 19-Nov-2017, 20-Nov-2017, 21-Nov-2017, 22-Nov-2017, 23-Nov-2017, 24-Nov-2017, 25-Nov-2017, 26-Nov-2017, 27-Nov-2017, 28-Nov-2017, 29-Nov-2017, 30-Nov-2017, 01-Dec-2017, 02-Dec-2017, 03-Dec-2017, 04-Dec-2017, 05-Dec-2017, 06-Dec-2017, 07-Dec-2017, 08-Dec-2017, 09-Dec-2017, 10-Dec-2017, 11-Dec-2017, 12-Dec-2017","data":"6550.22, 6635.41, 7301.42, 7815.03, 7786.88, 7817.14, 8007.65, 8255.59, 8059.8, 8268.03, 8148.94, 8250.97, 8707.4, 9284.14, 9718.29, 9952.5, 9879.32, 10147.37, 10883.91, 11071.36, 11332.62, 11584.82, 11878.43, 13540.98, 16501.97, 16007.43, 15142.83, 14869.8, 16762.11, 17276.39"}
Since you have provided your ajax result, this will not work with the chart generation. In your case result["labels"] is a string and you are just making a list with 1 element which is the whole string(which is not valid for the labels property and will not work). What you should do is split the string, format it correctly and then supply it as a list to the labels property. Easiest way would be to use the split() function, and in your case you could split by ", ". Although I would recommend to implement a better response if its possible (have it something like so: {"labels": ["13-Nov-2017", "14-Nov-2017", ...]}).
Hope this helps!
For the first time you can fill the chart with your own value, but when it is coming for dynamically appending data then you should remove the canvas element and regenerate it. So that your data will get appended dynamically on chart.
You can try something like this.
<canvas id="chartbtc" class="canvasChart"></canvas>
<script>
dynamicDataAppendOnChart(labels, data); // On page loading you will be having your own data so you can pass them, or if you want that to be happen with ajax when page loading itself you can trigger the click event.
$('#btnClick').trigger('click');
// You will be calling the function with click event...
$('#btnClick').on('click', function () {
var data = '', labels = '';
$.ajax({
url: url,
type: "POST",
data: data,
async: isAsync,
success: function (result) {
result = JSON.parse(result);
labels = result['labels'];
data = result['data'];
}
});
dynamicDataAppendOnChart(labels, data); // Now you can call the function by passing labels and data
});
function dynamicDataAppendOnChart() {
$('#chartbtc').remove();
$('#appendTheCanvasElement').append('<canvas id="chartbtc" class="canvasChart"><canvas>'); // This would create new canvas element every time and removes the older one.
var ctx = document.getElementById("chartbtc");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [labels],
datasets: [{
label: 'Market Price (USD)',
data: [data],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
}
}
});
}
</script>
Try This.
Declare label and data as
var labels = result['labels'].split(","); // Return Array of Strings Of labels
var data = JSON.parse("[" + result['data'] + "]");// return array of data
Chage
labels: [labels],
data: [data],
to
labels: labels,
data: data,
Because it already in array

Getting 'Chart is not defined' error when using chart.js in Meteor

I am using the official chart.js atmosphere package in my meteor application. I've tried running an example chart to see if I can pull it up however I am getting an issue saying "ReferenceError: Chart is not defined"
Here are the steps I took to installing the atmosphere package and running the code to produce the chart.
Installed the package with meteor add chart:chart
In my HTML I added the canvas tag calling the chart with it's informaiton
In the JS I added the function that creates the chart along with its relevant information
When I go to the page however, I just get an empty 400x400 image which is the canvas but there is no content there where the chart is supposed to be. Could someone assist me in figuring out what step I'm missing in order to get the chart to appear?
HTML
<template name="Home_page">
<canvas id="myChart" width="400" height="400"></canvas>
</template>
JS
import './home-page.html';
Template.Home_page.onRendered(function homePageOnRendered() {
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
});
Ok I forgot to add
import Chart from 'chart.js'
in the top of my js file. That fixed it.

How can i set piechart data's values with arrays name jschart

I use piechart with javascript(jschart graphic library). When i set the piechart data's values with arrays name the piechart doesn't work. if i use the static variable the piechart works how can i solve that?
this is static variables
function piechart()
{
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Galatasaray", "Fenerbahce", "Besiktas", "Diger"],
datasets: [{
data: [12,4,19,3],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
]
}]
},
options: {
responsive: true,
scales: {
beginAtZero: true
}
}
});
}
this is arrays name
function piechart()
{
int dizim=[5,9,8,7];
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Galatasaray", "Fenerbahce", "Besiktas", "Diger"],
datasets: [{
data: dizim,
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
]
}]
},
options: {
responsive: true,
scales: {
beginAtZero: true
}
}
});
}
please visit this site..
same question already answered
draw pie chart from arrays in highcharts
hope this works
You can make it work by changing int dizim=[5,9,8,7]; by var dizim=[5,9,8,7];

Chart.js addData is undefined when using SignalR

I'm attempting to call Chart.js's addData method from a signalR callback in order to dynamically add data to a chart based on server inputs. However, when the callback is triggered, the addData method on Chart.js is throwing an exception:
Uncaught TypeError: window.myChart.addData is not a function
Javascript:
var ctx = $("#myChart");
window.myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
responsive: true
});
$(function () {
var chart = $.connection.chartHub;
chart.client.addPointToChart = function () {
window.myChart.addData([20], "Magenta");
};
$.connection.hub.start().done(function () {
chart.server.start();
});
});
C# (hub code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace dvvWeb.Hubs
{
public class ChartHub : Hub
{
public void Start()
{
while (true)
{
Clients.All.addPointToChart();
System.Threading.Thread.Sleep(10000);
}
}
}
}
According to the documentation you should change your dataset directly and call update:
.update(duration, lazy) function to update your datas
// duration is the time for the animation of the redraw in miliseconds
// lazy is a boolean. if true, the animation can be interupted by other animations
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
I did a little test function on this fiddle:
setInterval(function(e) {
console.log(myDoughnutChart.data.datasets[0]);
myDoughnutChart.data.datasets[0].data.push(15);
myDoughnutChart.update();
}, 1000);
https://jsfiddle.net/Tintin37/weLoqyby/
Opened issue : https://github.com/chartjs/Chart.js/issues/1997
EDIT
For real time chart (I'm using signalr too, I use visjs)
http://visjs.org/examples/graph2d/15_streaming_data.html
Have a great day !

Categories

Resources