[Chartjs]-Charts.js – json output to graph

1👍

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/

0👍

no plan why it’s empty for me..

my database output is correct it think!

data.php

[{"day":"15","quantity":"72"},{"day":"16","quantity":"157"},{"day":"17","quantity":"130"},{"day":"18","quantity":"91"},{"day":"19","quantity":"96"},{"day":"20","quantity":"129"},{"day":"21","quantity":"140"},{"day":"22","quantity":"141"}]

index.html

<!DOCTYPE html>
<html>
<head>
    <title>a simple chart</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>
</html>

app.js

$.ajax({
type: 'POST',
url: 'data.php',
success: function (data) {
    lineChartData = JSON.parse(data); //parse the data into JSON

    var ctx = document.getElementById("mycanvas").getContext("2d");
    var myLineChart = new Chart(ctx, {
        type: 'line',
        data: lineChartData
    });
}
});

Leave a comment