'Putting C++ string in HTML code to show value on webserver

I've set up a webserver running on ESP8266 thats currently hosting 7 sites. The sites is written in plain HTML in each diffrent tab in the arduino ide. I have installed the library Pagebuilder to help with making everything look nice and run.

Except one thing. I have a button connected to my ESP8266 which by the time being imitates a sensor input. basicly when the button is pressed my integer "x" increments with 1. I also managed to make a string that replicates "x" and increments with the same value.

I also have a problem with Printing the IPadresse of the server, but thats not as important as the other.

My plan then was writing the string "score" (which contains x) into the HTML tab where it should be output. this obviously didnt work.

Things I've tried:

Splitting up the HTML code where I want the string to be printed and using client.println(""); This didnt work because the two libraries does not cooperate and WiFiClient does not find Pagebuilders server. (basicly, the client.println does nothing when I used it with Pagebuilder).

Reconstructing the HTML page as a literal really long string, and adding in the String with x like this: "html"+score+"html" and adding it into where the HTML page const char were. (basicly replacing the variable with the text that were in the variable). This did neighter work because the argument "PageElement" from Pagebuilder does only expect one string, and errors out because theres an additional string inside the HTML string.

I've tried sending it as a post req. but this did not output the value either.

I have run out of Ideas to try.


//root page

#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiClient.h>
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include <WebServer.h>
#endif
#include "PageBuilder.h"


#include "currentGame.h" //tab 1

#if defined(ARDUINO_ARCH_ESP8266)
ESP8266WebServer Server;
ESP8266WebServer  server;
#endif

int sensorPin = 2;    // button input
int sensorValue = 0;  
int x = 0;            // the int  x 
String score="";      //the string x will be in




PageElement CURRENT_GAME_ELEMENT(htmlPage1);
PageBuilder CURRENT_GAME("/current-game", {CURRENT_GAME_ELEMENT}); // this //only showes on href /current-game

void button() {
  sensorValue = analogRead(sensorPin); //read the voltage
  score="Team 1: "+String((int)x+1);   //"make" x a string
  if (sensorValue <= 10) {             // check if button is pressed
    x++;                               // increment x
    Serial.println(x);
    Serial.println(score);
    delay(100);
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(2, INPUT);
  WiFi.softAP("SSID", "PASS");
  delay(100);         
  CURRENT_GAME.insert(Server);     

  Server.begin();
}

void loop() {
Server.handleClient();
button();
}

// tab 1 

const char htmlPage1[] PROGMEM = R"=====(

/*
alot of HTML, basicly the whole website...

..............................................

*/

<div class="jumbotron">
            <div align="center">
            <h1 class="display-4">     score      </h1> //  <--- this is where 
                                                        //I want to print the 
                                                        //string:
            </div>
            </div>

            )====="; 

what I want to do is getting the value of the string score displayed on the website. If I put "score" directly into the HTML, the word score will be displayed, not the value. I want the value displayed.

Edit:

I have figured out how to make the string(score) be printed in the HTML code, thus, I only have to convert the HTML code string back to a char. explanation is in comment below.

Edit 2: (-------------------------solution-------------------------)

Many thanks for the help I've gotten and sorry for being so ignorant, its just so hard being so close and that thing doesnt work. but anyways, What I did was following Pagebuilders example, and making another element to print in current game..


String test(PageArgument& args) { 
  return score;
}

const char html[] = "<div class=\"jumbotron\"><div align=\"center\"><h1 class=\"display-4\">{{NAME}}</h1></div></div>";

PageElement FRAMEWORK_PAGE_ELEMENT(htmlPage0);
PageBuilder FRAMEWORK_PAGE("/", {FRAMEWORK_PAGE_ELEMENT});

PageElement body_elem(html, { {"NAME", test} });
PageElement CURRENT_GAME_ELEMENT(htmlPage1);
PageBuilder CURRENT_GAME("/current-game", { CURRENT_GAME_ELEMENT, body_elem});

suprisingly easy when I first understood it.. Thanks again.



Solution 1:[1]

This sort of thing is often done using magic tags in your markup that are detected by the server code before it serves the HTML and filled in by executing some sort of callback or filling in a variable, or whatever.

So with this in mind and hoping for the best, I nipped over to: PageBuilder on github and looked to see if there was something similar here. Good news! In one of the examples:

const char html[] = "hello <b>{{NAME}}</b>, <br>Good {{DAYTIME}}.";
 ...
PageElement body_elem(html, { {"NAME", AsName}, {"DAYTIME", AsDayTime} });

Where {{NAME}} and {{DAYTIME}} are magic tokens. AsName and AsDayTime are functions to be called when the respective tag is encountered while the page is being served.

EDIT: in response to a request to explain differently, I'm not convinced I can do a better job of explaining the code than the example on the library's own github page, so I'll try a wordy description instead:

When you want to serve a webpage to a client, the code needs to know what you want to serve. In the simplest case, it's a static page: the same every time. You can just write the HTML, stick it in a string an be done.

whole_page = "<html>My fixed content</html>";
webserver.serve(whole_page);

But you want some dynamic element(s). As noted, you can do it in a few ways, such as serving some static HTML, then the dynamic bit, then some more static HTML. It seems you've not had much luck like this, and it's rather clunky anyway.

Or you can pre-build a new string out of the three bits and serve that in one chunk, but that's also pretty clunky.

(Aside: taking big strings and adding them together is likely to be slow and memory intensive, two things you really don't want on a little CPU like the ESP8266).

So instead, you allow 'magic' markers in the HTML, using a marker in place of the dynamic content, and serve that instead.

whole_page = "<html>My dynamic content.  Value is {{my_value}}</html>";
webserver.serve(whole_page, ...);

The clever bit is that as the page is being served, the webserver is watching the text go by, and when it sees a magic tag, it stops and asks you to fill in the blank, then carries on as before.

Obviously, there is some processing overhead with watching for tags, and some programming overhead with telling it what tags to watch for and how to ask you for the data it needs.

Solution 2:[2]

You could try building your string first, then converting it to a const char like this: const char * c = str.c_str(); if you can't use a pointer you could try this:

string s = "yourHTML" + score + "moreHTML"; 
int n = s.length(); 
char char_array[n + 1]; 
strcpy(char_array, s.c_str());

additionally you could try the stringstream standard library

Solution 3:[3]

I got advice from a friend who told me I should make a unique argument where I wanted the string(x) and then using some syntax to replace it. I also took inspiration from you Jelle..

what I did was make a unique argument "VAR_CURRENT_SCORE" put that into the HTML where I want the score output, then convert htmlPage1 from a char to a string, use string.replace() and replace "VAR_CURRENT_SCORE" with the string(x) score. this workes as I can see in the serial monitor output. This is what I did:

//root page
String HTMLstring(htmlstringPage);
delay(100);
HTMLstring.replace("VAR_CURRENT_SCORE", score);
delay(50);
Serial.println("string:");
Serial.println(HTMLstring);

//tab 1 char htmlstringPage[] PROGMEM = R"=====(
        <div class="jumbotron">
        <div align="center">
        <h1 class="display-4">VAR_CURRENT_SCORE</h1>
        </div>
        </div>
        )====="; 

However, I still have a small problem left which is converting the string back to char to post it to the website.

Solution 4:[4]

To convert the string back:

request->send_P(200, "text/html", HTMLstring.c_str());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 CPlusPlusandHTMLguy
Solution 4 Solved Games