Hi,
starting from the ESP32 WebServer example 4_4_Multiple_Web_Pages I created a similar project, that gives temperature and humidity values every 10 seconds (the idea is later to read the values every 5 minutes).
The problem that I have, is that accessing the server with the browser I’m getting the complete page layout with the items titles, but without values (empty): only after 10 seconds, the delay time, the values are filled at the right place.
When later I’ll increase the delay time to 5 minutes, then it will be even worse, because I’ll have to wait 5 minutes to get the page completed with the values.
How can I modify the program so that a new browser accessing the page asks the server to get the sensor values immediately without to wait a possibly long delay? Is the solution using an appropriate function in the javascript of the page or inside the main.cpp?
Maybe also refreshing the browser page would be a good idea to ask the server for the actual values…
Many thanks for suggestions!
Best regards,
Enrico
Hi.
You need to add a Javascript function that makes a request to get the readings when the webpage loads.
Doesn’t your JavaScript have something like this?
// Get current sensor readings when the page loads
window.addEventListener('load', getReadings);
This will call a javascript function getReadings when you open the web page.
The function makes a request to get the latest readings.
// Function to get current readings on the web page when it loads
function getReadings() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
console.log(myObj);
var temp = myObj.temperature;
var hum = myObj.humidity;
plotTemperature(temp);
plotHumidity(hum);
}
};
xhr.open("GET", "/readings", true);
xhr.send();
}
See the JavaScript of project 3.3 and 3.2
I hope this helps.
Regards,
Sara
Hi Sara,
many thanks for your answer.
Yes I had already in the javascript files for every one of the webpages the code
window.addEventListener('load', getReadings);
and also
function getReadings() {
but my mistake was inside the getReadings function where in the call
xhr.open(“GET”, “/readings”, true);
I used “/<page-name>” instead of “/readings“.
Now the program seems to work as expected.
There are also an eventListener for “/readings” and another one for “/new_readings”.
What’s the difference? Why do we need both?
Many thanks and have a good day!
Best regards,
Enrico
Hi.
The /readings is when the web page loads, it makes a request on that URL.
The new_readings is the endpoint for the server-sent events.
Regards,
Sara