1

I have json data in DRF which run locally at url: http://127.0.0.1:8000/api/data/ like this :

[
{
    "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
}
]

I want to make a line chart based on all the data on field "vibration" and "moisture". And i've tried it with codes like this :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Try Chart</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>

<script>
function dspChrt(hum, vibrate) {
    hum = loadChart().hum;
    vibrate = loadChart().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)"
}]
}
});
}
</script>

<script>
var myVar = setInterval(loadChart, 60000); // updates chart every one minute

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);
    for (var i=0; i<data.length;i++) {
        hum = data[i].moisture;
        vibrate = data[i].vibration;
    }
    console.log('hum', hum);
    console.log('vibrate', vibrate);
    console.log('data', data);
    return data,hum,vibrate;
    dspChrt(hum, vibrate);            
}
}
request.open('GET', requestURL);
request.send(); // send the request
}
</script>

</head>

<body onload="loadChart()">
<div class="container">
<h2>Try Chart</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>

But it doesn't work, the data doesn't appear on the chart and in the inspect element of the web page only return the last data of "vibration" and "moisture". I want all the data in "vibration" and "moisture" to be plotted on the chart, not only the last one. this is the inspect element of the webpage : inspect-element-chart I think this is happen because format of the json. Anybody know how to fix it? I am still a newbie in programming. Thank you before

4
  • Is DRF - Django Rest Framework? And what do you expect will happen to the data every one minute? Is there a data logger on the server or something? See my answer, hopefully it helps you out. Commented Mar 17, 2020 at 15:53
  • @AlexL ya it's Django Rest Framework. I expect the chart will refresh and add the new data every one minute. There is no server yet, I still use localhost Commented Mar 18, 2020 at 3:25
  • @AlexL by the way, it works! Thank you! Commented Mar 18, 2020 at 3:57
  • Great! Good to hear! Commented Mar 18, 2020 at 4:26

1 Answer 1

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/[email protected]/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/[email protected]/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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.