Insert Data in current page from Arduino

Hello ,

Currently as beginner , I tried to add data in current page (html) from arduino without success (all tutorials shows reloading page or handling get request.

Here is my arduino code :

#include "WiFi.h"
#include "SPIFFS.h"   //
#include "ESPAsyncWebServer.h"
// the setup function runs once when you press reset or power the board
const char* ssid = "MyESP32AP";
const char* password = "testpassword";

IPAddress local_ip(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

const char* PARAM_INPUT_1 = "BTN_SEARCH";///"input1";

AsyncWebServer server(80);

void setup() 
{
    Serial.begin(115200);


    WiFi.softAP(ssid, password);

    WiFi.softAPConfig(local_ip, gateway, subnet);//

    Serial.println();
    Serial.print("IP :");
    Serial.println(WiFi.softAPIP());


    if (!SPIFFS.begin()) {
        Serial.println("An Error has occurred while mounting SPIFFS");
        return;
    }

   
    server.on("/panel", HTTP_GET, [](AsyncWebServerRequest* request) {
    
        request->send(SPIFFS, "/index_html.html", "text/html");

        });
   
    server.on("/get", HTTP_GET, [](AsyncWebServerRequest* request) {

        String inputParam = PARAM_INPUT_1;
 
        String inputMessage = request->getParam(PARAM_INPUT_1)->value();
      

        if (inputMessage == "searchAP") 
        {
            request->send(SPIFFS, "/index_html.html", "text/html");
            //Here is my problem , I would like to keep the same page and insert the data !
        }    

/*
            request->send(200, "text/html", "HTTP GET request sent to your ESP on input field ("
                + inputParam + ") with value: " + inputMessage +
                "
<a href=\"/panel\">Return to Home Page</a>");

*/
        });

    server.on("/test.js", HTTP_GET, [](AsyncWebServerRequest* request) {
        request->send(SPIFFS, "/test.js", "text/javascript");
        });


    server.begin();
    //WiFi.mode(WIFI_STA);
     //WiFi.disconnect();
    delay(100);
    Serial.println("Hello From VS2019 !");
    Serial.println("Setup done");
}

// the loop function runs over and over again until power down or reset
void loop() {}
        if (inputMessage == "searchAP")
        {
            request->send(SPIFFS, "/index_html.html", "text/html");
            //Here is my problem , I would like to keep the same page and insert the data !
        }

You want to edit /index_html.html on the fly (dynamically) before sending it ?
I suppose you could read it line by line and stream it out or write to another SPIFFS file and then send it (not ideal for flash memory, though)

Can you give an example of the sort of change you want to make. There may be other ways of achieving the same thing.

Okay okay I tought that too (edit line by line) but there are no other solutions ? (and yes I would like to get data dynamically on same page)

Example : I have the url 192.168.1.1/panel which is my panel to get/send data.

I would like to receive those data keeping the url 192.168.1.1/panel (if possible without creating new files or streaming original file)

How big is the file: “/index_html.html” ?

  1. You could embed a place holder such as “@<>@” in the file. Get the whole thing into a String object and replace the placeholder with your new text using a the replace() method, then send the String object.

  2. You could use javascript to do a return to the server to collect the supplementary information to be added to index.html and let javascript add it. This can also be useful if you have a fully static html page which you want to populate with variable data.

edit
post crossed with the OP

Html Source :

<!DOCTYPE html> <html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
  <title>Panel Control</title>
  <style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}
  body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;} h3 {color: #444444;margin-bottom: 50px;}
  .button {display: block;width: 80px;background-color: #3498db;border: none;color: white;padding: 13px 30px;text-decoration: none;font-size: 25px;margin: 0px auto 35px;cursor: pointer;border-radius: 4px;}
  .button-on {background-color: #3498db;}
  .button-on:active {background-color: #2980b9;}
  .button-off {background-color: #34495e;}
  .button-off:active {background-color: #2c3e50;}
  p {font-size: 14px;color: #888;margin-bottom: 10px;}
  </style>
   <script src="test.js"></script>
  </head>
  <body>
  <h1>ESP32 Web Server</h1>
  <h3>Using Access Point(AP) Mode</h3>
      <button onclick="openAlert()">Click me</button>
  
  <form action="/get">

  input1: <input type="text" name="input1">


  <input type="submit" name="BTN_SEARCH" value="searchAP">
</form>

  </body>
  </html>

And yes with JS I prefer than placeholder (if i get more information to set , I will prefer not to have full placeholders in my html code)

const char* JS_PARAM = "TTT";

server.on("/test.js", HTTP_GET, [](AsyncWebServerRequest* request) {
        request->send(SPIFFS, "/test.js", "text/javascript");

        if (request->getParam(JS_PARAM)->value()=="Hello !") 
        {

            Serial.println("Works !");
        }

        });

This is my code to handle JS but how can I pass my params from js to webserver ? I tried that but doesn't work !

I just use this simple code to test the params from JS (it works) but doesn't work from arduino code !

function openAlert(TTT) 
{
    //window.alert("Hello World from vs 2019 !");
    window.alert(TTT);
}

You have to use XMLHttpRequest() or similar in javascript to make a return call to the server to fetch more data.

This example:

   // http://stackoverflow.com/questions/3038901/how-to-get-the-response-of-xmlhttprequest
    // needs error handling
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            document.getElementById("jsonIn").value = xhr.responseText  ;
        }
     }
     xhr.open('GET', '/json', false);   
     xhr.send(null);

issues a call back to the server with path /json and puts the result in an HTML field jsonIn. That is a json format string and further javasscript parses it and populates the remaining HTML fields on the document. That way, the initial page which is sent is static HTML. The data for the fields is then retrieved indirectly via the onLoad event in the browser.

The whole project from which that example is extracted is here: https://forum.arduino.cc/index.php?topic=559652.0 . Look at files WebServerHtml.h, WebServer.cpp and WebServer.h

Use a page processor

        request->send(SPIFFS, "/run-protocol-3.html", String(), false, Processor_Protocol);
//Template Processor methods
String Processor_Protocol(const String & var) {
  if (var == "FORM_DISABLED_RUNSTEP2") {
    return String("disabled");
/// etc

In the file have %FORM_DISABLED_RUNSTEP2% text where you want the replacement to happen
see GitHub - me-no-dev/ESPAsyncWebServer: Async Web Server for ESP8266 and ESP32