I wanted to load an image on a webpage with just the press of a button using AJAX.
So I came up with the idea of setting up a setInterval Javascript function that loads every second the html image... but how can I change the picture if I cant change the const char* with the code I need?
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ESPmDNS.h>
#include "LITTLEFS.h"
AsyncWebServer server(80);
const char* ssid = "ssid";
const char* password = "password";
const char image_html[] PROGMEM = R"rawliteral(
<div id="image"></div>
)rawliteral";
const char webpage[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><body>
<div id="image"></div>
<script>
setInterval(function()
{ loadImage();}, 1000);
function loadImage() {
var img = new XMLHttpRequest();
img.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200)
{
document.getElementById("image").innerHTML = this.responseText;
}
};
img.open("GET", "image_html", true);
img.send();
}
</script>
</body></html>
)rawliteral";
void setup() {
if(!LITTLEFS.begin()){
// Serial.println("An Error has occurred while mounting LITTLEFS");
return;
}
pinMode(4,INPUT_PULLUP);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (MDNS.begin("webpage")) {
// Serial.println("MDNS responder started");
}
server.on("/image", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(LITTLEFS, "/image.png", "image/png");
});
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/html", webpage);
});
server.on("/image_html", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/html", image_html);
});
}
void loop() {
if (digitalRead(4) == 0) {
const char image_html[] PROGMEM = R"rawliteral(
<div id="image"><img src="/image.png"</img></div>
)rawliteral";
//I cannot do this of course
}
}
Something like this.