0

I would like to modify the following HTML/JS code in order to fulfil the following requirements:

  1. Select only "temp" data in my JSON file
  2. xAxis should be "point" and not datetime
  3. I don't want a refresh every X seconds but only when the page is refreshed.
<script>
var chartT = new Highcharts.Chart({
  chart:{ renderTo : 'chart-temperature' },
  title: { text: 'BME280 Temperature' },
  series: [{
    showInLegend: false,
    data: []
  }],
  plotOptions: {
    line: { animation: false,
      dataLabels: { enabled: true }
    },
    series: { color: '#059e8a' }
  },
  xAxis: { type: 'datetime',
    dateTimeLabelFormats: { second: '%H:%M:%S' }
  },
  yAxis: {
    title: { text: 'Temperature (Celsius)' }
    //title: { text: 'Temperature (Fahrenheit)' }
  },
  credits: { enabled: false }
});
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var x = (new Date()).getTime(),
          y = parseFloat(this.responseText);
      //console.log(this.responseText);
      if(chartT.series[0].data.length > 40) {
        chartT.series[0].addPoint([x, y], true, true, true);
      } else {
        chartT.series[0].addPoint([x, y], true, false, true);
      }
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 30000 ) ;

and my JSON looks like this:

[
{"point":184,"temp":20.5,"humidity":49.5,"weight1":0,"weight2":0},
{"point":185,"temp":20.6,"humidity":49.7,"weight1":0,"weight2":0},
{"point":186,"temp":20.6,"humidity":49.6,"weight1":0,"weight2":0}
]

right now, the command

xhttp.open("GET", "/temperature", true);
  xhttp.send();

will return my whole JSON file in a string

But in the chart I only want to display the "temp" information.

vib
  • 199
  • 2
  • 13

1 Answers1

1

You need to parse your JSON to JS object and use series.setData method. For example:

function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      const data = JSON.parse(this.responseText);
      const processedData = data.map(dataEl => [dataEl.point, dataEl.temp]);
      chartT.series[0].setData(processedData);
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}
getData();

Also, please check this thread about new ways of sending requests: Parsing JSON from XmlHttpRequest.responseJSON


Live demo: http://jsfiddle.net/BlackLabel/p9gaxmju/

API Reference: https://api.highcharts.com/class-reference/Highcharts.Series#setData

ppotaczek
  • 36,341
  • 2
  • 14
  • 24