Patrick Duke Schauer Patrick Duke Schauer - 6 months ago 77
JSON Question

charts.js - json output to graph

I want to dispay in a bar graph the days and the quantity.
I have following json output.(data.php) for each day the quantity.

[{"day":"2017-11-15","quantity":"72"},{"day":"2017-11-16","quantity":"157"},{"day":"2017-11-17","quantity":"130"},{"day":"2017-11-18","quantity":"91"},{"day":"2017-11-19","quantity":"96"}]


output.html

<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>

<!-- 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/app.js"></script>
</body>




and thats the app.js

$(document).ready(function(){
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
console.log(data);
var day = [];
var quantity = [];

for(var i in data) {
day.push(data[i].day);
quantity.push(data[i].quantity);
}

var chartdata = {
labels: day,
datasets : [
{
label: 'DAYS',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: quantity
}
]
};

var ctx = $("#mycanvas");

var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});


but it's always empty. but why? Any idea? Also instead of the day theres only undefined on the bottom line.

Answer Source

Here is the main idea

data.forEach(function(packet) {

  labelsData.push(packet.day);
  datasetData.push(parseFloat(packet.quantity));

});

for example

var dataJSON = [{
  "day": "2017-11-15",
  "quantity": "72"
}, {
  "day": "2017-11-16",
  "quantity": "157"
}, {
  "day": "2017-11-17",
  "quantity": "130"
}, {
  "day": "2017-11-18",
  "quantity": "91"
}, {
  "day": "2017-11-19",
  "quantity": "96"
}];

var labelsData = [];
var datasetData = [];

dataJSON.forEach(function(packet) {

  labelsData.push(packet.day);
  datasetData.push(parseFloat(packet.quantity));

});

var chartdata = {
  type: 'bar',
  data: {
    labels: labelsData,
    datasets: [{
      label: 'DAYS',
      data: datasetData
    }]
  }
}

Working JSFiddle

https://jsfiddle.net/4v3nt7sL/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download