In this tutorial we are getting data from web browser using HTML forms. ESP8266 is configured as server. When user clicks on button or text box data that we want to read it in ESP8266 (NodeMCU). This is we are demonstrating in example. before moving to ESP8266, let’s understand basics of HTML forms.
What are HTML forms?
HTML Forms are one of the main points of interaction between a user and a web site or ESP8266. They allow users to send data to the web site. Most of the time that data is sent to the web server, but the web page can also intercept it to use it on its own.
An HTML Form is made of one or more widgets. Those widgets can be text fields (single line or multiline), select boxes, buttons, checkboxes, or radio buttons. Most of the time those widgets are paired with a label that describes their purpose — properly implemented labels are able to clearly instruct both sighted and blind users on what to enter into a form input.
The main difference between a HTML form and a regular HTML document is that most of the time, the data collected by the form is sent to a ESP8266 web server. In that case, you need to set up a web server to receive and process the data. We are setting ESP8266 as web server.
The <form> Element
The HTML <form>
element defines a form that is used to collect user input:
<form> . form elements . </form>
An HTML form contains form elements.
Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and more.
The <input> Element
The <input>
element is the most important form element.
The <input>
element can be displayed in several ways, depending on the type attribute.
Here are some examples:
Type | Description |
---|---|
<input type=”text”> | Defines a one-line text input field |
<input type=”radio”> | Defines a radio button (for selecting one of many choices) |
<input type=”submit”> | Defines a submit button (for submitting the form) |
The Action Attribute
The action
attribute defines the action to be performed when the form is submitted.
Normally, the form data is sent to a web page on the server when the user clicks on the submit button.
In the example above, the form data is sent to a page on the server called “/action_page”. This page contains a server-side script that handles the form data:
<form action=”/action_page“>
If the action
attribute is omitted, the action is set to the current page.
The Method Attribute
The method
attribute specifies the HTTP method (GET or POST) to be used when submitting the form data:
<form action=”/action_page” method=”get”>
<form action=”/action_page” method=”post”>
When to Use GET?
The default method when submitting form data is GET.
However, when GET is used, the submitted form data will be visible in the page address field:
/action_page?firstname=Mickey&lastname=Mouse
Notes on GET:
- Appends form-data into the URL in name/value pairs
- The length of a URL is limited (about 3000 characters)
- Never use GET to send sensitive data! (will be visible in the URL)
- Useful for form submissions where a user wants to bookmark the result
- GET is better for non-secure data, like query strings in Google
When to Use POST?
Always use POST if the form data contains sensitive or personal information. The POST method does not display the submitted form data in the page address field.
Notes on POST:
- POST has no size limitations, and can be used to send large amounts of data.
- Form submissions with POST cannot be bookmarked
Step 1: Creating web form
Open notepad and create simple html web page. Test/open this html page in web browser to see results and do necessary adjustments, before uploading it to ESP8266.
<!DOCTYPE html> <html> <body> <h2>Circuits4you<h2> <h3> HTML Form ESP8266</h3> <form action="/action_page"> First name:<br> <input type="text" value="Mickey"> <br> Last name:<br> <input type="text" name="lastname" value="Mouse"> <br><br> <input type="submit" value="Submit"> </form> </body> </html>
Open web browser and test your web form
Step 2: Creating ESP8266 as Web Server
Basic details are covered below. For more details refer this post
Ref: https://circuits4you.com/2016/12/16/esp8266-web-server-html/
Step 3: Handling web form data
Step 1: Connect to WiFi
WiFi.begin(ssid, password); //Connect to your WiFi router Serial.println(""); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Step 2: Create web server on root
server.on("/", handleRoot); //Which routine to handle at root server.begin(); //Start server
Root page request handler
void handleRoot() { String s = MAIN_page; //Read HTML contents server.send(200, "text/html", s); //Send web page }
Similarly we create form handler, form action is set to “action_page”
server.on("/action_page", handleForm); //form action is handled here
We can read the form data or user sent data through forms using server.arg.
String firstName = server.arg(“firstname”);
//=============================================================== // This routine is executed when you press submit //=============================================================== void handleForm() { String firstName = server.arg("firstname"); String lastName = server.arg("lastname"); Serial.print("First Name:"); Serial.println(firstName); Serial.print("Last Name:"); Serial.println(lastName); String s = "<a href='/'> Go Back </a>"; server.send(200, "text/html", s); //Send web page }
Complete code to handle web form data.
Enter your SSID and Password then upload the code to ESP8266
/* * ESP8266 (NodeMCU) Handling Web form data basic example * https://circuits4you.com */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> const char MAIN_page[] PROGMEM = R"=====( <!DOCTYPE html> <html> <body> <h2>Circuits4you<h2> <h3> HTML Form ESP8266</h3> <form action="/action_page"> First name:<br> <input type="text" name="firstname" value="Mickey"> <br> Last name:<br> <input type="text" name="lastname" value="Mouse"> <br><br> <input type="submit" value="Submit"> </form> </body> </html> )====="; //SSID and Password of your WiFi router const char* ssid = "YourSSID"; const char* password = "YourPassword"; ESP8266WebServer server(80); //Server on port 80 //=============================================================== // This routine is executed when you open its IP in browser //=============================================================== void handleRoot() { String s = MAIN_page; //Read HTML contents server.send(200, "text/html", s); //Send web page } //=============================================================== // This routine is executed when you press submit //=============================================================== void handleForm() { String firstName = server.arg("firstname"); String lastName = server.arg("lastname"); Serial.print("First Name:"); Serial.println(firstName); Serial.print("Last Name:"); Serial.println(lastName); String s = "<a href='/'> Go Back </a>"; server.send(200, "text/html", s); //Send web page } //============================================================== // SETUP //============================================================== void setup(void){ Serial.begin(9600); WiFi.begin(ssid, password); //Connect to your WiFi router Serial.println(""); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } //If connection successful show IP address in serial monitor Serial.println(""); Serial.print("Connected to "); Serial.println("WiFi"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //IP address assigned to your ESP server.on("/", handleRoot); //Which routine to handle at root location server.on("/action_page", handleForm); //form action is handled here server.begin(); //Start server Serial.println("HTTP server started"); } //============================================================== // LOOP //============================================================== void loop(void){ server.handleClient(); //Handle client requests }
Step 4: Results and testing of received data
After uploading open serial monitor with 9600 baud rate. First you will see only IP address.
Enter the IP address in web browser to open the web page.
Click on submit button and observer the serial monitor
This way you can get the web form data.
FAQ
Q1. Is it possible to stay on same page after pressing button?
ANS: Yes it is possible using server.sendHeader. Add these lines at the bottom of action page handler function.
Read More
How to control multiple LEDs? Read here
In this example you can find same logic can be applied to multiple relay control. that makes a home automation system.
How to read ESP8266 ADC data and display it in web page without refresh? Read here
This is little advanced application uses javascript ajax to update and control LED.
How to upload ADC Sensor data to a real IoT Cloud Web Server? Read here
In this example we upload adc data to things speak server.
Create Advance Cool IoT Widgets Like analog dial shown below. Read more here
Is it possible to stay on same page and keep old data after pressing Submit button?
I’m having troubles implementing this code. The IDE compiler is saying that “class Wifi server has no member named .arg”
It seems that this library do not include this method
Sir can i convert this to AP please help
Yes, You can use web forms in AP mode also.