Live data in a SPIFFS web page


I wrote a comment about this on the ESP8266 forum & realise that it was a little terse, so I'll try to explain better.

The ESP8266 has a file system & it's possible to serve web pages from it, just like a real webserver.

Often, we would like to present live or real time data from (eg) a sensor & it's not immediately obvious how to do this without constructing the page on the fly.
We want to embed the data in an otherwise static page.

This can be achieved using javascript. A collection of useful tools is illustrated at http://www.w3schools.com/lib/w3data.js

I am using the W3IncludeHTML function which looks like this:

function w3IncludeHTML() {
  var z, i, a, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    if (z[i].getAttribute("w3-include-html")) {
      a = z[i].cloneNode(false);
      file = z[i].getAttribute("w3-include-html");
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          a.removeAttribute("w3-include-html");
          a.innerHTML = this.responseText;
          z[i].parentNode.replaceChild(a, z[i]);
          w3IncludeHTML();
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }

You don't need to understand this to make things happen. Save this as a file on SPIFFS. I call it 'w3-include-HTML.js'

In SPIFFS web pages where I want to insert data I put the lines:

<div w3-include-html="content.html"></div>
<script src="w3-include-HTML.js"></script>

The page requests 'content.html' from the server. I deal with it like this:

server.on("/content.html", live_data);  //can serve live data from sensor

And a live_data() function reads a sensor and does something like this:

  void bmp_send()   //response if BMP180 is connected
  {
     // format sensor data as a table
      String webpage = "<p><table border='2'><tbody><tr><td>Pressure  <br></td><td>" + String(pressure) + " hPa" + "<br></td></tr>";
      webpage += "<tr><td>Temperature  <br></td><td>" + String(temp) + " C" + "<br></td></tr></tbody></table><br>";
      server.send(200, "text/html", webpage);  //and serve it...
  }


In this example a web page is delivered with a table embedded.



Ian Sexton 2016