String value on HTML page

Hello world!
I need to show the value of a String on a web-page instead of “ESP32 Login Page” text.
The String variable name is machineName.
The html code:

"<form name='loginForm'>"
    "<table width='20%' bgcolor='A09F9F' align='center'>"
        "<tr>"
            "<td colspan=2>"
                "<center><font size=4><b>ESP32 Login Page</b></font></center>"
                "
"

Which web server are you using? If it's the ESPAsyncWebServer, the template capability will likely do exactly what you need.

I’m using the example from ESP32 for OTAWebUpdater
#include <WebServer.h>
So I think it’s not using the ESPAsyncWebServer.
What do you mean with “the template capability”? I know nothing about HTML.

Please post the code you are using

The entire code is:

#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>

String machineName = "Press";
const char* host = "esp32";
const char* ssid = "xxx";
const char* password = "xxxx";

WebServer server(80);

/*
 * Login page
 */

const char* loginIndex = 
 "<form name='loginForm'>"
    "<table width='20%' bgcolor='A09F9F' align='center'>"
        "<tr>"
            "<td colspan=2>"
                "<center><font size=4><b>ESP32 Login Page</b></font></center>"
                "
"
            "</td>"
            "
"
            "
"
        "</tr>"
        "<td>Username:</td>"
        "<td><input type='text' size=25 name='userid'>
</td>"
        "</tr>"
        "
"
        "
"
        "<tr>"
            "<td>Password:</td>"
            "<td><input type='Password' size=25 name='pwd'>
</td>"
            "
"
            "
"
        "</tr>"
        "<tr>"
            "<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
        "</tr>"
    "</table>"
"</form>"
"<script>"
    "function check(form)"
    "{"
    "if(form.userid.value=='admin' && form.pwd.value=='admin')"
    "{"
    "window.open('/serverIndex')"
    "}"
    "else"
    "{"
    " alert('Error Password or Username')/*displays error message*/"
    "}"
    "}"
"</script>";
 
/*
 * Server Index Page
 */
 
const char* serverIndex = 
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
   "<input type='file' name='update'>"
        "<input type='submit' value='Update'>"
    "</form>"
 "<div id='prg'>progress: 0%</div>"
 "<script>"
  "$('form').submit(function(e){"
  "e.preventDefault();"
  "var form = $('#upload_form')[0];"
  "var data = new FormData(form);"
  " $.ajax({"
  "url: '/update',"
  "type: 'POST',"
  "data: data,"
  "contentType: false,"
  "processData:false,"
  "xhr: function() {"
  "var xhr = new window.XMLHttpRequest();"
  "xhr.upload.addEventListener('progress', function(evt) {"
  "if (evt.lengthComputable) {"
  "var per = evt.loaded / evt.total;"
  "$('#prg').html('progress: ' + Math.round(per*100) + '%');"
  "}"
  "}, false);"
  "return xhr;"
  "},"
  "success:function(d, s) {"
  "console.log('success!')" 
 "},"
 "error: function (a, b, c) {"
 "}"
 "});"
 "});"
 "</script>";

/*
 * setup function
 */
void setup(void) {
  Serial.begin(115200);

  // Connect to WiFi network
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  /*use mdns for host name resolution*/
  if (!MDNS.begin(host)) { //http://esp32.local
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  /*return index page which is stored in serverIndex */
  server.on("/", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", loginIndex);
  });
  server.on("/serverIndex", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", serverIndex);
  });
  /*handling uploading firmware file */
  server.on("/update", HTTP_POST, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
    ESP.restart();
  }, []() {
    HTTPUpload& upload = server.upload();
    if (upload.status == UPLOAD_FILE_START) {
      Serial.printf("Update: %s\n", upload.filename.c_str());
      if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_WRITE) {
      /* flashing firmware to ESP*/
      if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_END) {
      if (Update.end(true)) { //true to set the size to the current progress
        Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
      } else {
        Update.printError(Serial);
      }
    }
  });
  server.begin();
}

void loop(void) {
  server.handleClient();
  delay(1);
}

It does not appear to me the synchronous web server you're using supports template processing. You might want to take a look at some examples of the AsyncWebServer, which does include template processing. It is a far better overall server, and quite simple to setup. It's the only one I would use. The template processing allows you to setup a simple callback function that will fill fields of the form "%SomeIdentifierHere%in the HTML AS it is being sent to the client. In your HTML you would replace the string "ESP32 Login Page" with something like %ESP32LoginPageLabel%, and when the client requests the page, the server would call your callback function, passing the string "ESP32LoginPageLabel" as an argument. You use that string to identify what template is being requested, and return the value, which then gets inserted into the HTML in place of the template string.

The String variable name is machineName.

Does the variable have to be a String or could it be a string instead ?

If you really must you could do something like this :

const char * part1 = "start ";
String part2 = "middle";
const char * part3 = " end";

void setup()
{
  Serial.begin(115200);
  while (!Serial);
  Serial.println((String)part1 + part2 + (String)part3);
}

void loop()
{
}

If you really must you could do something like this :

This is the most obvious solution, totally acceptable really. Let’s not worry about using up a bit of the heap as long as it local (it is an ESP32 after all)
so you want a String (or string) here somewhere

"<center><font size=4><b>ESP32 Login Page</b></font></center>"

Actually the most efficient would be to change the const char* to Strings local to the callback function. In the interest of overview i suggest first we actually create a callback function and change

server.on("/", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", loginIndex);
  });

to

server.on("/", HTTP_GET, handleRoot);

and the function:

void handleRoot {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", loginIndex);
  }

Now let’s just declare the whole page bit by bit on the heap:

void handleRoot {
    String s =  "<form name='loginForm'>"
    "<table width='20%' bgcolor='A09F9F' align='center'>"
        "<tr>"
            "<td colspan=2>"
                "<center><font size=4><b>";

     s +=  "ESP32 Login Page";  // you can change this as you please

     s += </b></font></center>"
                "
"
            "</td>"
            "
"
            "
"
        "</tr>"
        "<td>Username:</td>"
        "<td><input type='text' size=25 name='userid'>
</td>"
        "</tr>"
        "
"
        "
"
        "<tr>"
            "<td>Password:</td>"
            "<td><input type='Password' size=25 name='pwd'>
</td>"
            "
"
            "
"
        "</tr>"
        "<tr>"
            "<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
        "</tr>"
    "</table>"
"</form>"
"<script>"
    "function check(form)"
    "{"
    "if(form.userid.value=='admin' && form.pwd.value=='admin')"
    "{"
    "window.open('/serverIndex')"
    "}"
    "else"
    "{"
    " alert('Error Password or Username')/*displays error message*/"
    "}"
    "}"
"</script>";

    server.sendHeader("Connection", "close");
    server.send(200, "text/html", s);
  }

That should work, i always get a little iffy with these single and double quotes and no semicolon, but if it works as a char* you can do it to a String. And this is as memory efficient as it gets. So anyway you got the webupdater to work, great !!

Thank you guys.
Problem solved! :smiley:

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