[Chartjs]-How to handle data API from Django Rest Framework in Chart.js

2👍

I’ve tried to set up a sandbox example without using the request and having the JSON as a JS Object in the JS code.

const JSONdata = [
{
    "id": 2,
    "timestamp": "2020-03-15T11:46:10+07:00",
    "vibration": 3,
    "moisture": 70,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 6,
    "timestamp": "2020-03-15T12:00:10+07:00",
    "vibration": 3,
    "moisture": 75,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 7,
    "timestamp": "2020-03-15T13:00:10+07:00",
    "vibration": 3,
    "moisture": 75,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 8,
    "timestamp": "2020-03-16T07:00:00+07:00",
    "vibration": 3,
    "moisture": 80,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
}
]
function dspChrt(hum, vibrate) {

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
  label: 'Humidity',
  data: hum, // json value received used in method
  backgroundColor: "rgba(153,255,51,0.4)"
}, {
  label: 'Vibration',
  data: vibrate,
  backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}

// Not sure how this is expected to work? Is the Data a Stream?
//var myVar = setInterval(loadChart, 60000); // updates chart every one minute

function loadChart(){
  var data, hum = [], vibrate = [];
  
/*doing it with the JSON already in the JS for this example:

  var requestURL = 'http://127.0.0.1:8000/api/data'; //URL of the JSON data
  var request = new XMLHttpRequest({mozSystem: true}); // create http request  

  request.onreadystatechange = function() {
   if(request.readyState == 4 && request.status == 200) {
      data = JSON.parse(request.responseText);
*/    
      data = JSONdata;
      for (var i=0; i<data.length;i++) {
          hum.push(data[i].moisture);
          vibrate.push(data[i].vibration);
      }
      /*
      console.log('hum', hum);
      console.log('vibrate', vibrate);
      console.log('data', data);
      */      
      dspChrt(hum, vibrate);            
/*doing it with the JSON already in the JS for this example:       
    }
  } 
request.open('GET', requestURL);
request.send(); // send the request
*/
}
loadChart();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Try Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<body onload="loadChart()">
<div class="container">
<h2>Try Chart</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>

The most important thing is to set up your hum and vibrate variables as empty arrays:

function loadChart(){
      var data, hum = [], vibrate = [];
      ...
}

And then to push onto them each item’s moisture and vibration property (each item is each object in your JSON array):

for (var i=0; i<data.length;i++) {
      hum.push(data[i].moisture);
      vibrate.push(data[i].vibration);
}

By this at the end of the for-loop the variables are:

hum = [70, 75, 75, 80]
vibrate = [3, 3, 3, 3]

Also, you had your functions calling each other but neither of the functions being invoked.

So you should have this function with arguments:

function dspChrt(hum, vibrate) {

    var ctx = document.getElementById('myChart').getContext('2d');
    ...
}

And don’t need to then call the other function loadChart again from this as the values are already passed in – we already have them

function loadChart(){
      var data, hum = [], vibrate = [];
      ...
          /*
          console.log('hum', hum);
          console.log('vibrate', vibrate);
          console.log('data', data);
          */      
          dspChrt(hum, vibrate); 
      ...
}

And notice this function doesn’t need to return anything, we just need to call dspChart(hum, vibrate)

And finally, we need to invoke/call our loadChart() function to make this happen and the Chart to be created.

loadChart();

Finally, the output is this (click Show code snippet and then run it):

enter image description here

And so finally, the code with the XMLHttpRequest happening is the following, but it obviously won’t work on Stack Overflow:

function dspChrt(hum, vibrate) {

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
  label: 'Humidity',
  data: hum, // json value received used in method
  backgroundColor: "rgba(153,255,51,0.4)"
}, {
  label: 'Vibration',
  data: vibrate,
  backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}

function loadChart(){
  var data, hum = [], vibrate = [];
  
  var requestURL = 'http://127.0.0.1:8000/api/data'; //URL of the JSON data
  var request = new XMLHttpRequest({mozSystem: true}); // create http request  

  request.onreadystatechange = function() {
   if(request.readyState == 4 && request.status == 200) {
      data = JSON.parse(request.responseText);
      //data = JSONdata;
      for (var i=0; i<data.length;i++) {
          hum.push(data[i].moisture);
          vibrate.push(data[i].vibration);
      }
      /*
      console.log('hum', hum);
      console.log('vibrate', vibrate);
      console.log('data', data);
      */      
      dspChrt(hum, vibrate);                
    }
  } 
request.open('GET', requestURL);
request.send(); // send the request

}

loadChart();
//var myVar = setInterval(loadChart, 60000); // updates chart every one minute
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Try Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<body onload="loadChart()">
<div class="container">
<h2>Try Chart</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>

Leave a comment