Displaying data on webpage - async server and javascript: SOLVED by changing to server sent events

I’m building a device to log the output from my solar panels by counting led pulses from the meter using an ESP32 Devkit.
The device logs data to SPIFFS and displays it on a web page using some code from this tutorial

The problem I am having is that the data is correctly displayed on my web page - but does not auto-update. This is supposed to be handled with javascript on the web page and server responses from the ESP32

I’ve included what I hope are the relevant bits of the project here.

<p>
    <span class="sensor-labels">Max Watts: </span>
    <span id="mwatts">%MWATTS%</span>
    <span class="units"> W</span>
  </p>

javascript:

<script>
 setInterval(fmW,10000);   //max count
   function fmW(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("mwatts").innerHTML = this.responseText;
      }
    };
    xhttp.open("GET", "/mwatts", true);
    xhttp.send();
  }
  </script>

the request handler:

//adapted from  https://randomnerdtutorials.com/esp8266-web-server-spiffs-nodemcu/
// Replaces placeholder with value
String processor(const String& var) {
  Serial.println(var);
  if (var == "STATE") {
    if (digitalRead(ledPin)) {
      ledState = "ON";
    }
    else {
      ledState = "OFF";
    }
    Serial.print(ledState);
    return ledState;
  }
   else if (var == "MWATTS") {
    return getmWatts();
  }
}

String getmWatts(){
  return String(mWatts);
}

and the code to set up the asynch server in “setup”

  // Route to update MWATTS
  server.on("/mwatts", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/plain", getmWatts().c_str());
  });

  server.begin(); //start web server

I’ve never worked with Ajax so don’t know the answer.

If updating the complete page is not an issue, you can use a meta tag as described in HTML meta http-equiv Attribute (search for refresh)

Thanks @Sterretje but refreshing the complete page makes it flash every time it refreshes. I cant really use that approach, I need to get the ajax working.

After considerable wasted time I changed to using server sent events - which worked first time, required less code and was much simpler to implement.

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.