Currently, I am engrossed in a project that involves utilizing ESP32. I'm obtaining data from various sensors and transmitting it to a webpage hosted on the same board. After doing some research online, I learned that it's considered "better" to transmit all sensor data using the json method. Therefore, my function for retrieving and sending data looks like this:
void handle_readings()
{
String results_json = "{ \"data\": " + Data +
"," + "\"hour\": " + Hour +
"," + "\"ambient_temp1\": " + AmbientTemp + " }";
server.send(200, "application/json", results_json);
}
On testing the above function in the serial monitor, I observed the following data:
{"data": Sunday, 12/4/2020,"hour": 20:53,"ambient_temp1": 25.75}
I stumbled upon a script that can retrieve only one piece of data and display it on the page. Here is the script:
function fetchData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("DATA").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "readings", true);
xhttp.send();
}
This is the code on my index page that displays data on the webpage:
const char initial_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
<title>My First Test</title></head>
<html>
<body>
<div id="page">
<h1>System XYZ</h1>
<div>
Data: <span id="DATA">ND</span><br>
Time: <span id="TIME">ND</span><br>
Ambient Temperature: <span id="AMBIENTTEMP1">ND</span>
</div>
<script>
setInterval(function() {
// Call a function repeatedly with a 1-second interval
fetchData();
}, 1000);
//Function to toggle an LED on my board
function sendInfo(led) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LEDState").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "setLED?LEDstate="+led, true);
xhttp.send();
}
function fetchData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "readings", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("TIME").innerHTML = jsonResponse.hour;
document.getElementById("AMBIENTTEMP1").innerHTML = jsonResponse.ambient_temp1;
}
else {
console.log(this.status);
}
};
}
</script>
</div>
</body>
</html>
)=====";
The main issue I'm facing now is how to adapt this script to fetch values from multiple sensors as described in the aforementioned function. Can anybody assist me with this modification? I appreciate any help you can provide! Thank you in advance :)