1

It's probably over a decade since last I played around with JavaScript, so here goes. I am trying to display a graph from either my back-end database and/or my ESP32 micro-controller. Easy to generate a static HTML/CSS/JavaScript graph from and example, but I need the graph to update with real time data every second. I can get the JavaScript to call the database via XMLHttpRequest and it returns the data, but I have no clue about how to get it back into the variable that updates the graph.

I found more or less the charts that I require for a project on https://www.amcharts.com/.

// using chart.setTimeout method as the timeout will be disposed together with a chart
 chart.setTimeout(randomValue, 1000);

function randomValue() {
    //hand.showValue(Math.random() * 1000, 1000, am4core.ease.cubicOut); // <----- sample code supplied
    //hand.showValue(550); // <---- my test code which works

    // after some googling I found this...
    function reqListener () {
        console.log(this.responseText);
    //alert(oReq.responseText); // <---- when un-commented I can see my data that the database is returning every second, just an integer value and nothing else.
    }

    var oReq = new XMLHttpRequest();
    oReq.addEventListener("load", reqListener);
    oReq.open("GET", 'http://myurl.com');
    oReq.send();

    hand.showValue(oReq.responseText); <<<<<< what do I put in the () to show the same data that the alert above displays correctly?

    chart.setTimeout(randomValue, 1000); // < original supplied sample code
}

Nothing happens... and I don't have a clue :)

Oscar
  • 13
  • 5
  • Move `hand.showValue(oReq.responseText);` inside `function reqListener ()` – rodrigoap Aug 17 '19 at 13:46
  • In short: You just can't. As a sidenote, I warmly recommend using [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) nowadays. – Jonas Wilms Aug 17 '19 at 14:22
  • " Move hand.showValue(oReq.responseText); inside function reqListener () – rodrigoap 46 mins ago I tried that but it did not work - thanks – Oscar Aug 17 '19 at 14:37
  • As I said it's been a while since last I looked at JavaScript. I will have a look at fetch() thanks. – Oscar Aug 17 '19 at 14:42

1 Answers1

0

XMLHttpRequest requires you to add an event listener and wait for the load event. This will tell you once the request has completed and then you can do something with the response.

Take a look at this website for a more detailed description: https://javascript.info/xmlhttprequest

Tameem Safi
  • 728
  • 5
  • 6
  • Got it working but the console gives an error : InvalidStateError: responseText is only available if responseType is '' or 'text'. – Oscar Aug 17 '19 at 14:35