Chartjs-Live update the charts.js graph on a web page using json data received from a remote server

0👍

You have typo in the for function name loadChart.
The variable declarations and function definitions are needed to be added before being used.
Reduced the length of array to 7 instead of 10.

Here is updated code snippet. I’ve added the temperature as well. 😉

var humArray = [];
var temArray = [];
var N = 7;
for (i = 0; i < N; i++) {
  humArray.push(0);
  temArray.push(0);
}

function loadChart() { //fetches json data & calls dspChart() to render graph 
  var wData, hum, tem;
  var requestURL = 'https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s'; //URL of the JSON data
  var request = new XMLHttpRequest({
    mozSystem: true
  }); // create http request
  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      wData = JSON.parse(request.responseText);
      hum = wData.humidity;
      tem = wData.temperature;
      humArray.shift();
      humArray.push(hum);
      temArray.shift();
      temArray.push(tem);
      dspChrt(humArray, temArray);
    }
  }
  request.open('GET', requestURL);
  request.send(); // send the request
  //dspChrt(hum);
}
var myVar = setInterval(loadChart, 60000);

function dspChrt(humArray, temArray) { // to be called by loadChart() to render live chart
  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: humArray, // json value received used in method
        backgroundColor: "rgba(153,255,51,0.4)"
      }, {
        label: 'Temprature',
        data: temArray,
        backgroundColor: "rgba(255,153,0,0.4)"
      }]
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<body onload="loadChart();">
  <div class="container">
    <h2>Weather Update</h2>
    <div>
      <canvas id="myChart"></canvas>
    </div>
  </div>
</body>

Hope it helps.

Leave a comment