Javascript - how to pars json into two lists - javascript

I am trying to work with chaert.js and I am using ajax to get the json data.
My Json file looks like this:
[
{
"timestamp": "00:00:00.000000",
"true_count": 0
},
{
"timestamp": "01:00:00.000000",
"true_count": 0
},
{
...
}
]
I need to get time stamp into my _label variable and i need to get true_count into my _data variable.
Here is what i tried so far:
$(document).ready(function(){
var _data =[];
var _labels = [];
$.ajax({
url: "chart_data",
type: "get",
success: function(response) {
full_data = JSON.parse(response);
full_data.forEach(function(key,index){
_data = key.true_count;
_labels= key.timestamp;
});
//_data = [full_data['true_count']];
//_labels = [full_data['timestamp']];
},
});
});
I am not getting any error but my chart is not showing the data. I am very certain that i am not parsing the data properly. Can you please tell me what am i doing wrong?
As i mentioned, i just need _data to store all true_count and _labels to store all timestamps.
Thank you
So here is the full version of my code with the updates you suggested. For some reason my chart is not showing the data, it actually seems that is only showing the first record which is 00:00:000 with 0 true_count.
/* chart.js chart examples */
$(document).ready(function(){
var _data =[];
var _labels = [];
$.ajax({
url: "chart_data",
type: "get",
success: function(response) {
full_data = JSON.parse(response);
full_data.forEach(function(key,index) {
_data.push(key.true_count);
_labels.push(key.timestamp);
});
//_data = [full_data['true_count']];
//_labels = [full_data['timestamp']];
},
});
// chart colors
var colors = ['#007bff','#28a745','#333333','#c3e6cb','#dc3545','#6c757d'];
/* large line chart */
var chLine = document.getElementById("chLine");
var chartData = {
labels:_labels,
datasets: [
{
data:_data,
backgroundColor: [
'rgba(42, 157, 244, 0.1)'
],
borderColor: [
'rgba(42, 157, 244, 1)',
'rgba(33, 145, 81, 0.2)',
],
borderWidth: 1
}]
};
if (chLine) {
new Chart(chLine, {
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false
}
}
});
}
;
});

You're actually almost there. The problem is that your current version just reassigns the variables:
full_data.forEach(function(key,index) {
_data = key.true_count;
_labels= key.timestamp;
});
The result is that you end up with the last value only, since you're constantly replacing the previous value. What you want to achieve is add each element to your lists:
full_data.forEach(function(key,index) {
_data.push(key.true_count);
_labels.push(key.timestamp);
});

Related

Frontend and backend for chart using chartjs, mongodb, and controller

I am new to generating a chart using the ajax mechanism and chartjs. It seems that I managed to generate the graph but they are plotted incorrectly. Please enlighten me on how I could improve. Would really appreciate Thank you
Following is my code in javascript to plot chart
var ctx = document.getElementById('myChart').getContext('2d');
$.ajax({
url:"/dashboard",
type:"POST",
data: {},
error: function() {
alert("Error");
},
success: function(data, status, xhr) {
debugger
// declare all variables to draw chart
var chartDim = {};
var chartDim = data.chartDim;
var xLabels = data.labels;
var vLabels = [];
var vData = [];
let newValues =[]
// get from database to push to draw the chart
for (const [key, values] of Object.entries(chartDim)) {
vLabels.push(key);
let newValues = values.map(myFunction);
debugger;
vData.push(newValues);
}
debugger
var myChart = new Chart(ctx, {
data: {
labels: xLabels,
datasets: []
},
options: {
responsive: false
}
});
// draw to chart
debugger
for (i= 0; i < vLabels.length; i++ ) {
myChart.data.datasets.push({
label: vLabels[i],
type: "bar",
// borderColor: '#'+(0x1ff0000+Math.random()*0xffffff).toString(16).substr(1,6),
borderColor: '#'+(0x1100000+Math.random()*0xffffff).toString(16).substr(1,6),
backgroundColor: "rgba(249, 238, 236, 0.74)",
data: vData[i],
spanGaps: true
});
myChart.update();
}
}})
This happens because while making your chart you push each data point as a new dataset. Instead you just need to use a single dataset and pass the data array to it like so:
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: xLabels,
datasets: [{
borderColor: '#' + (0x1100000 + Math.random() * 0xffffff).toString(16).substr(1, 6),
backgroundColor: "rgba(249, 238, 236, 0.74)",
data: vData,
spanGaps: true
}]
},
options: {
responsive: false
}
});

ChartJS doesn't read data unless I am debugging

My chart doesn't read my array data unless I hit breakpoints while obtaining the data through JSON url. If I am debugging, my chart renders okay, if not, it's blank. Please help. Thank you!
<script>
var labels = [];
var payments = [];
jQuery.getJSON("<?=base_url()?>Admin/getJSONWeeklyDates", function(data) {
labels = data;
});
jQuery.getJSON("<?=base_url()?>Admin/getJSONWeeklyPayments", function(data) {
payments = data;
});
</script>
<script>
( function ( $ ) {
"use strict";
// single bar chart
var ctx = document.getElementById( "singelBarChart" );
ctx.height = 150;
var myChart = new Chart( ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: "Payments",
data: payments,
borderColor: "rgba(0, 123, 255, 0.9)",
borderWidth: "0",
backgroundColor: "rgba(0, 123, 255, 0.5)"
}
]
},
options: {
scales: {
yAxes: [ {
ticks: {
beginAtZero: true
}
} ]
}
}
} );
} )( jQuery );
</script>
Note: When I console log the labels' and payments' array length it shows 0 even though it has 2 values when I access the array through console after page load.

Using dynamic data to plot Chart.js but show cant read property "skip" of undefined

i am new to angular js and chart js. I want to plot graph with chart js with dynamic data, here is the result when server return:
I get the "nameArray" and "values" from the server and want to put inside chart.js
$scope.drawChart = function () {
console.log("start draw");
var name = $scope.result.nameArray
var value = $scope.result.values
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: name,
datasets: [{
// label: "My First dataset",
label: name,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
// data: [0, 10, 5, 2, 20, 30, 45],
data: value,
}]
},
// Configuration options go here
options: {}
});
}
And my angular controller part:
$scope.result = [];
$scope.getPosts = function () {
$http({
method: 'POST',
url: 'http://localhost/test.php',
data: {
"action": "getchartdata",
"username": "username",
"deptname": "departname",
"officename": "office",
"softwarename": "this",
"StartTime": "time",
"EndTime": "time",
"ipaddress": "10.0.90.1"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
transformRequest: function (data) {
var str = [];
for (var p in data)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(data[p]));
return str.join("&");
}
}).then(function (result) {
$scope.result = result.data
console.log($scope.result);
console.log($scope.result.nameArray)
$scope.drawChart();
}, function (error) {
console.log("error")
});
};
I get this error:
I not sure what happening there, or is that chartjs doest support like this?

chart.js ajax pushing another dataset always "undefined"

Following is my javascript Code, but the only thing really relevant is the last function. I want to update the Chart to add another dataset, without reloading the Page. But for reason the added dataset is always undefined. The commented-out line, which uses the exact same array of data, on the other hand works. Since I'm new to javascript I'm not sure, if I missed something obvious, or if chart.js just doesn't support this kind of thing at all.
const CHART = document.getElementById("lineChart");
var dts1 = [
{
label: "Abfall gesamt",
data: Abfall_gesamt,
}
];
var dts2 = [
{
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
}
];
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: Jahr,
datasets: dts1
}
});
function myFunction(){
//lineChart.data.datasets[0].data = Abfall_schadstoff;
lineChart.data.datasets.push(dts2);
lineChart.update();
}
The issue is, you are defining your datasets (dts1 and dts2) as an array. They should be an object, like so ...
var dts1 = {
label: "Abfall gesamt",
data: Abfall_gesamt,
};
var dts2 = {
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
};
and then, when generating the chart, set datasets value as ...
datasets: [dts1]
ᴅᴇᴍᴏ
const CHART = document.getElementById("lineChart");
var Abfall_gesamt = [1, 2, 3];
var Abfall_schadstoff = [4, 5, 6]
var dts1 = {
label: "Abfall gesamt",
data: Abfall_gesamt,
backgroundColor: 'rgba(255, 0, 0, 0.2)'
};
var dts2 = {
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
backgroundColor: 'rgba(0, 0, 255, 0.2)'
};
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: ['Jahr', 'Mahr', 'Kadr'],
datasets: [dts1]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
}
});
function myFunction() {
//lineChart.data.datasets[0].data = Abfall_schadstoff;
lineChart.data.datasets.push(dts2);
lineChart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button id="add" onclick="myFunction()">Add Dataset</button>
<canvas id="lineChart" height="190"></canvas>

How to dynamically set backgroundColor and borderColor barchart unsing Chart.js

I am trying to set the backgroundColor and borderColor based on the dynamic data I get, I am also trying to alternate the color if the "score" number is even or odd I can't find a way to get it done. Any suggestions is very appreciated.
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 800px;
height: 600px;
}
</style>
<!-- javascript -->
<script type="text/javascript" src="jquery-1.11.min.js"></script>
<script type="text/javascript" src="Chart.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
//url: "test.html",
//method: "GET",
success: function(data) {
// test data
var data = [
{
"Serverid":"1",
"score":"37"
},
{
"Serverid":"2",
"score":"60"
},
{
"Serverid":"3",
"score":"35"
},
{
"Serverid":"4",
"score":"41"
},
{
"Serverid":"5",
"score":"50"
},
{
"Serverid":"6",
"score":"70"
}
// ... it can be more than that
];
var Server = [];
var score = [];
for(var i in data) {
Server.push("Server " + data[i].Serverid);
score.push(data[i].score);
}
var chartdata = {
labels: Server,
datasets : [
{
label: 'Score I',
backgroundColor: [
// even color
'rgba(255, 99, 132, 0.2)',
// odd color
'rgba(75, 192, 192, 0.2)'
],
borderColor: [
// even color
'rgba(255,99,132,1)',
// odd color
'rgba(153, 102, 255, 1)'
],
borderWidth: 1,
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}, // end success
error: function(data) {
console.log(data);
alert(data);
}
}); // end ajax
});
</script>
</head>
<body>
<br> Test Bar 3 <br>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
</body>
</html>
Thank you!
There isn't really anything special that is required to dynamically set your bar background and border colors, it all just depends on what logic you want to use to set the colors.
Per the API, chart.js allows you to pass in an array of colors (instead of just a simple color) in your bar chart dataset for backgroundColor and borderColor. You can control data point colors because the index in this array maps to the index in your data array. In other words, if you want to color the 2nd data point blue, then insert blue into the 2nd index of the color array.
So all you need to do is iterate over your dynamic data and build your data, backgroundColor, and borderColor arrays per your logic (alternating colors). Here is an example.
function getData(data) {
var dataSize = Math.round(Math.random() * 100);
var evenBackgroundColor = 'rgba(255, 99, 132, 0.2)';
var evenBorderColor = 'rgba(255,99,132,1)';
var oddBackgroundColor = 'rgba(75, 192, 192, 0.2)';
var oddBorderColor = 'rgba(153, 102, 255, 1)';
var labels = [];
var scoreData = {
label: 'Mid-Term Exam 1',
data: [],
backgroundColor: [],
borderColor: [],
borderWidth: 1,
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
};
for (var i = 0; i < dataSize; i++) {
scoreData.data.push(window.randomScalingFactor());
labels.push("Score " + (i + 1));
if (i % 2 === 0) {
scoreData.backgroundColor.push(evenBackgroundColor);
scoreData.borderColor.push(evenBorderColor);
} else {
scoreData.backgroundColor.push(oddBackgroundColor);
scoreData.borderColor.push(oddBorderColor);
}
}
return {
labels: labels,
datasets: [scoreData],
};
};
Here is a codepen example demonstrating what I mean.
Now, to map this back to your specific example, you would simply call your getData() method from within your $.ajax success callback (or just copy the essence of my example directly into your callback). Here is an example of what your code (supplied from your question) would look like calling the above getData() function.
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
//url: "test.html",
//method: "GET",
success: function(data) {
var ctx = $("#mycanvas");
// create our chart and pass it the data returned from the ajax request
var barGraph = new Chart(ctx, {
type: 'bar',
// pass the data returned from the ajax request so we can assemble it
data: getData(data),
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}, // end success
error: function(data) {
console.log(data);
alert(data);
}
}); // end ajax
});
</script>
Or just take a look at this other example showing the solution mapped to your code.
public class TheServerController : Controller
{
public ActionResult Index()
{
return View();
}
//Json Function To Call The Data
public JsonResult DummyServerData()
{
List<TheServer> allDummyServers = ServerRepository.GetAllServers();
Chart _chart = new Chart();
//Create And Load Server-Names-Array
_chart.labels = allDummyServers.Select(x => x.ServerId).ToArray();
//Create Scores-Array
int[] scores = allDummyServers.Select(x => x.Score).ToArray();
//Create An Empty-Colors-Array With The Same Size As Scores.Count
string[] colours = new string[scores.Length];
for (int i = 0; i < scores.Length; i++)
{
//Load The Colours-Array With As Per Index(i) Of The Scores-Array
//By Calling The Coloring Function From Repository
colours[i] = ServerRepository.GetColourStringNameBasedOnScore(scores[i]);
}
_chart.datasets = new List<Datasets>();
List<Datasets> _dataSet = new List<Datasets>();
_dataSet.Add(new Datasets()
{
label = "Server Scores",
data = scores,// Adding The Scores To Dataset
backgroundColor = colours,// Adding The Colours To Dataset
borderWidth = "1"
});
_chart.datasets = _dataSet;
return Json(_chart, JsonRequestBehavior.AllowGet);
}
}

Categories

Resources