JSON : Convert Json For Chart CanvasJS - javascript

I'm working with chart using Canvas JS , I have problem to fetch data .
I have result json_encode() like this :
[{“jumlah_berita”:2,”nama_kategori”:”Music”},{“jumlah_berita”:1,”nama_kategori”:”Sport”},{“jumlah_berita”:1,”nama_kategori”:”Agama”},{“jumlah_berita”:0,”nama_kategori”:”Teknologi”},{“jumlah_berita”:1,”nama_kategori”:”Pendidikan”},{“jumlah_berita”:0,”nama_kategori”:”Cinta”},{“jumlah_berita”:0,”nama_kategori”:”coba test”}]
I already read documentation Canvas JS about Accepted Data CanvasJS, It's mean my json not valid.
My Question is, How to convert JSON
From:
[
{“jumlah_berita”:2,”nama_kategori”:”Music”},
{“jumlah_berita”:1,”nama_kategori”:”Sport”},
{“jumlah_berita”:1,”nama_kategori”:”Agama”},
{“jumlah_berita”:0,”nama_kategori”:”Teknologi”},
{“jumlah_berita”:1,”nama_kategori”:”Pendidikan”},
{“jumlah_berita”:0,”nama_kategori”:”Cinta”},
{“jumlah_berita”:0,”nama_kategori”:”coba test”}
]
To :
[{y:2,label:"Music"},
{y:1,label:"Sport"},
{y:1,label:"Agama"},
{y:0,label:"Teknologi"},
{y:2,label:"Pendidikan"}]
Thank's
It's My code to make Chart
<script>
window.onload = function() {
var tampil_kategori = '<?= $tampil_kategori ?>';
var newdataPoints = JSON.parse(tampil_kategori);
var jumlahBerita = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
theme: "light2", // "light1", "light2", "dark1", "dark2"
title: {
text: "Jumlah Berita(per Kategori)"
},
data: [{
type: "column",
dataPoints: newdataPoints
}]
});
jumlahBerita.render();
}
</script>

You can use map:
const to = from.map(item => ({
y: item.jumlah_berita,
label: item.nama_kategori
}));
EDIT
window.onload = function() {
var tampil_kategori = [
{“jumlah_berita”:2,”nama_kategori”:”Music”},
{“jumlah_berita”:1,”nama_kategori”:”Sport”},
{“jumlah_berita”:1,”nama_kategori”:”Agama”},
{“jumlah_berita”:0,”nama_kategori”:”Teknologi”},
{“jumlah_berita”:1,”nama_kategori”:”Pendidikan”},
{“jumlah_berita”:0,”nama_kategori”:”Cinta”},
{“jumlah_berita”:0,”nama_kategori”:”coba test”}
];
// map here --------------------------------
var newdataPoints = tampil_kategori.map(item => ({
y: item.jumlah_berita,
label: item.nama_kategori
}));
// -----------------------------------------
var jumlahBerita = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
theme: "light2", // "light1", "light2", "dark1", "dark2"
title: {
text: "Jumlah Berita(per Kategori)"
},
data: [{
type: "column",
dataPoints: newdataPoints
}]
});
jumlahBerita.render();
}

Related

How can my Chart.js just update when data in SQL change?

I build a web app in MVC using SignalR to update real-time data. I can display my chart with real-time data from SQL but it just updates by the time set in setInterval. But now I want my chart to just update when my data in SQL SERVER changes. I have tried many ways but it's not correct. Can you help me with the algorithm? Thank you.
Here is my code :
<!--Chart-->
<script>
var ctx = document.getElementById("percent-chart2");
var colorarray = ['#00b5e9', '#fa4251', '#006400'];
var pre_vals = 0;
//
var myVar = setInterval(GetValue, 1000);
function GetValue() {
var val1 = parseFloat(document.getElementById("tblValue").innerHTML);
var val2 = parseFloat(document.getElementById("tblValue1").innerHTML);
var vals = [val1, val2, 2000];
return vals;
}
if (ctx) {
ctx.height = 209;
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [
{
label: "My First dataset",
//data: [GetValue, GetValue, GetValue],
data: GetValue(),
backgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
hoverBackgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
borderWidth: [
0, 0, 0
],
hoverBorderColor: [
'transparent',
'transparent',
'transparent'
]
}
],
labels: [
'STATION 1',
'STATION 2',
'STATION 3'
]
},
options: {
maintainAspectRatio: false,
responsive: true,
cutoutPercentage: 57,
animation: {
animateScale: true,
animateRotate: true
},
legend: {
display: false,
position: 'bottom',
labels: {
fontSize: 14,
fontFamily: "Poppins,sans-serif"
}
},
tooltips: {
titleFontFamily: "Poppins",
xPadding: 15,
yPadding: 10,
caretPadding: 0,
bodyFontSize: 16,
}
}
});
}
function UpdateChart(datachart, data, color) {
datachart.data.datasets.pop();
datachart.data.datasets.push({
data: data,
backgroundColor: color,
hoverBackgroundColor: color
});
datachart.update();
}
setInterval(function () {
const my_val = GetValue();
//var updatedata = [my_val, my_val, 2000];
var updatedata = my_val;
UpdateChart(myChart, updatedata, colorarray);
}, 10000);
</script>
The way I handle this is by adding a client call with the dataset after the database update has completed. This way you only update when that update is called.
Here is a rough example off the top of my head:
public void UpdateDB(int updatedData)
{
//DB work to commit the updatedData
....
//Query your dataset into an serialized updatedDataset
....
//Call a method to create an array (updatedColors) of colors based on the the Count of updatedDataset
....
//Send data to client(s)
Clients.All.yourclientfunction(updatedDataset, updatedColors);
}

Cant display data from JSON in canvasjs

hi and sorry for silly question i miss some part of code and cant figure it out, I did from this lesson https://canvasjs.com/javascript-charts/json-data-api-ajax-chart/ and when I'm editing code to put my json api and values nothing happens....(values from json are telemetry only 'timestamp' and 'cpu' value)
my code is :
window.onload = function() {
var dataPoints = [];
var cpuPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "consume timeline"
},
axisY: {
title: "cpu use",
titleFontSize: 24,
},
data: [{
type: "column",
yValueFormatString: "#,### Units",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Date(data[i].timestamp),
y: data[i].cpu
});
}
chart.render();
}
$.getJSON("http://192.168.13.60:12345/api/metric/cpu", addData);
}
please can somebody help me figure it out. I think i miss some variable to declare

Cant Generate pie chart using chartjs from JSON

I can't generate pie chart using canvas.JS. I already iterate them through loop.
JSON itself return value like below
[[{"label":"belum","x":1},{"label":"sudah","x":5}]]
I am using below code to get JSON data.
<script type="text/javascript">
$(document).ready(function () {
var abc = [];
$.getJSON("json/data_wilayah1.php", function (result) {
for( var i = 0; i < result.length; i++) {
abc.push({ label: result[i].label, y: result[i].y });
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
text: "Ketersediaan Perangkat Jasa Akses Internet Redesain USO"
},
toolTip:{
shared: true,
},
data: [
{
type:"pie",
name: "{label}",
legendText: "{label}",
showInLegend: true,
toolTipContent: "{label}: <strong>{x}%</strong>",
indexLabel: "{label} - {x}%",
dataPoints: abc
}
]
});
chart.render();
}
});
});
</script>
I think it's just a typo in looping.
abc.push({ label: result[i].label, y: result[i].y });
Do you have Y property in your response ?
In your Json response it's X so this result[i].y will return undefined.
I think you're supplying undefined value to co-ordinate.
This is the one which is not working
This is a working one (Updated)

multiple charts js in page but with same tooltips (about last chart)

I have more doughnut charts in one page, every chart have different data but I show the same tooltips. It's tooltips of the last chart. I don't found the problem.
This is js code:
var idList = [];
// --------------------
// Memo ID list...
// --------------------
jQuery('.idKQI').each(function (i) {
idList.push( jQuery(this).text() );
});
var idListLength = idList.length;
// ------------------
// Doughnut loop...
// ------------------
var dataDoughnutChart = {
labels: [
'KO',
'OK'
],
datasets: [{
data: [30,70],
backgroundColor: [
'#DF0101', // red
'#31B404' // green
]
}]
};
var optionsDoughnutChart = {
maintainAspectRatio: false,
responsive: true,
legend: {
display: false
},
tooltips: {
mode: 'dataset'
}
};
var idLav;
var ctxDoughnut;
var labelAdd;
var errati;
var esatti;
for (var i = 0, max = idListLength; i < max; i++) {
idLav = '#' + idList[i] + "_chartDoughnut";
ctxDoughnut = jQuery(idLav);
labelAdd = jQuery(idLav).data("labeladd");
errati = jQuery(idLav).data("errati");
esatti = jQuery(idLav).data("esatti");
dataDoughnutChart.labels[0] = 'Errati' + labelAdd;
dataDoughnutChart.labels[1] = 'Esatti' + labelAdd;
dataDoughnutChart.datasets[0].data[0] = errati;
dataDoughnutChart.datasets[0].data[1] = esatti;
var myDoughnutChart = new Chart(ctxDoughnut, {
type: 'doughnut',
data: dataDoughnutChart,
options: optionsDoughnutChart
});
}
If I have two doughnut chart, in witch in the first chart datasets.data = [10,90], and in the second chart datasets.data = [2,98], the tooltips for all two chart show 'Errati: 2' and 'Esatti: 98'. It's values like the second chart.
I'm also try to use an array for var dataDoughnutChart like:
var myDoughnutChart = new Chart(ctxDoughnut, {
type: 'doughnut',
data: dataDoughnutChart[i],
options: optionsDoughnutChart
});
but don't resolve.
Thanks for your help.
Resolved like below:
// .....
configDoughnutList.push(
{
type: 'doughnut',
data: {
datasets: [{
data: [
30,
70
],
backgroundColor: [
'#DF0101', // rosso
'#31B404' // verde
],
label: 'daughnut_163'
}],
labels: [
'Errati',
'Corretti'
]
},
options: {
responsive: true,
legend: {
display: false
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
mode: 'dataset'
}
}
}
);
configDoughnutList[i].data.datasets[0].data[0] = errati;
configDoughnutList[i].data.datasets[0].data[1] = esatti;
configDoughnutList[i].data.labels[0] = 'Errati' + labelAdd;
configDoughnutList[i].data.labels[1] = 'Esatti' + labelAdd;
window.myDoughnut = new Chart(ctxDoughnut, configDoughnutList[i]);

highcharts on IE9

I have two charts which are produced through a xml data. but it doesn't work on IE9.
Here the code:
var chart;var chartB;
jQuery(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginTop: 160
},
title: {
text: 'Wochen\u00FCbersicht',
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Minuten'
},
},
the series are filled from xml
series: []
};`load Data from xml file`
// Load the data from the XML file
$.get('Woche.xml', function(xml) {
// Split the lines
var $xml = $(xml);
// push categories
$xml.find('categories Monat').each(function(i, category) {
options.xAxis.categories.push($(category).text());
});
// push series
$xml.find('series').each(function(i, series) {
var seriesOptions = {
name: $(series).find('name').text(),
data: []
};
// push data points
$(series).find('data Minuten').each(function(i, Minuten) {
seriesOptions.data.push(
parseInt($(Minuten).text())
);
});
// add it to the options
options.series.push(seriesOptions);
set color
Highcharts.setOptions({ colors: ['#faebd7', '#00ffff ', '#000000', '#0000ff', '#8a2be2', '#7fff00', '#00008b', '#008000', '#ff1493', '#800000', '#ffa500', '#006400', '#ffff00', '#008080', '#ff0000', '#000080', '#bdb76b', '#20b2aa', '#ffd700', '#00ffff',] });
});
var chart = new Highcharts.Chart(options);
});
here begins the second chart
var options2 = {
chart: {
renderTo: 'containerB',
type: 'column',
},
title: {
text: 'Monats\u00FCbersicht',
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Minuten'
},
},
series: []
};
// Load the data from the XML file
$.get('Monat.xml', function(xml) {
// Split the lines
var $xml = $(xml);
// push categories
$xml.find('categories Monat').each(function(i, category) {
options2.xAxis.categories.push($(category).text());
});
// push series
$xml.find('series').each(function(i, series) {
var seriesOptions = {
name: $(series).find('name').text(),
data: []
};
// push data points
$(series).find('data Minuten').each(function(i, Minuten) {
seriesOptions.data.push(
parseInt($(Minuten).text())
);
});
// add it to the options
options2.series.push(seriesOptions);
Highcharts.setOptions({ colors: ['#faebd7', '#00ffff ', '#000000', '#0000ff', '#8a2be2', '#7fff00', '#00008b', '#008000', '#ff1493', '#800000', '#ffa500', '#006400', '#ffff00', '#008080', '#ff0000', '#000080', '#bdb76b', '#20b2aa', '#ffd700', '#00ffff',] });
});
var chartB = new Highcharts.Chart(options2);
});
});
Looking at the JSON options for each chart - you've a trailing comma after yAxis title, which isn't supported with IE.

Categories

Resources