In many IoT Applications we monitor sensor data and we want to display it in wab page. Web page requires frequent refresh to get the update from ESP32. To solve this problem you have two options, first is refresh page with HTML Tag: ex. refresh at every 30 seconds.
<head>
<meta http-equiv=”refresh” content=”30″>
</head>
In this tutorial I will show you how to display ADC data and update without refreshing web page. You can do a lot of things with this. At the end we will see some advance applications of this. To make this possible we need to use javaScript Ajax.
Tools you need
only ESP32, Laptop and USB cable
What you will learn?
- ESP32 Ajax web page to display and update sensor data without refresh.
- Getting data from ESP32 without page refresh and update it in web page dynamically. such as ADC values or temperature readings.
HTML and Java Script, AJAX basics
AJAX is about updating parts of a web page, without reloading the whole page.
What is AJAX?
AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
How ESP32 AJAX Works ?
In ESP32 NodeMCU we create two pages on server. First that loads as normal webpage and second webpage is behind the scene i.e. AJAX.
AJAX is Based on Internet Standards
AJAX is based on internet standards, and uses a combination of:
- XMLHttpRequest object (to exchange data asynchronously with a server)
- JavaScript/DOM (to display/interact with the information)
- CSS (to style the data)
- XML (often used as the format for transferring data)
Read More on Ajax at https://www.w3schools.com/asp/asp_ajax_intro.asp
Create Web Page with AJAX
How to create a web page in ESP and uploading it read this post ?
Make your HTML page and test it in browser. Then make it header file as shown in below code. DON’T JUST CHANGE THE EXTENSION TO .h
Create index.h file near to your final sketch. Copy and paste below code. Program is commented well. You can read more on HTML and AJAX at w3schools.com
index.h File
const char MAIN_page[] PROGMEM = R"=====( <!DOCTYPE html> <html> <style> .card{ max-width: 400px; min-height: 250px; background: #02b875; padding: 30px; box-sizing: border-box; color: #FFF; margin:20px; box-shadow: 0px 2px 18px -4px rgba(0,0,0,0.75); } </style> <body> <div class="card"> <h4>The ESP32 Update web page without refresh</h4><br> <h1>Sensor Value:<span id="ADCValue">0</span></h1><br> <br><a href="https://circuits4you.com">Circuits4you.com</a> </div> <script> setInterval(function() { // Call a function repetatively with 2 Second interval getData(); }, 2000); //2000mSeconds update rate function getData() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("ADCValue").innerHTML = this.responseText; } }; xhttp.open("GET", "readADC", true); xhttp.send(); } </script> </body> </html> )=====";
ESP32 Web Server Program Main INO file
/* * ESP32 AJAX Demo * Updates and Gets data from webpage without page refresh * https://circuits4you.com */ #include <WiFi.h> #include <WiFiClient.h> #include <WebServer.h> #include "index.h" //Web page header file WebServer server(80); //Enter your SSID and PASSWORD const char* ssid = "........."; const char* password = "........."; //=============================================================== // 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 } void handleADC() { int a = analogRead(A0); String adcValue = String(a); server.send(200, "text/plane", adcValue); //Send ADC value only to client ajax request } //=============================================================== // Setup //=============================================================== void setup(void){ Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); /* //ESP32 As access point WiFi.mode(WIFI_AP); //Access Point mode WiFi.softAP(ssid, password); */ //ESP32 connects to your wifi ----------------------------------- WiFi.mode(WIFI_STA); //Connectto your wifi WiFi.begin(ssid, password); Serial.println("Connecting to "); Serial.print(ssid); //Wait for WiFi to connect while(WiFi.waitForConnectResult() != WL_CONNECTED){ Serial.print("."); } //If connection successful show IP address in serial monitor Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //IP address assigned to your ESP //---------------------------------------------------------------- server.on("/", handleRoot); //This is display page server.on("/readADC", handleADC);//To get update of ADC Value only server.begin(); //Start server Serial.println("HTTP server started"); } //=============================================================== // This routine is executed when you open its IP in browser //=============================================================== void loop(void){ server.handleClient(); delay(1); }
Testing
Make WiFi network configuration changes as per your network. Upload the program and test it. Open serial monitor to observe the IP address and other actions.
Results
Open Serial monitor and get the IP address
Enter the IP address in web browser
In many application you may want to use jQuery and Bigger size HTML, CSS files and images. You can get clear idea from these two advanced posts
Hi, how can I add more sensors?
I found the solution for multiple sensors:
http://plnkr.co/edit/7DyTmdRdWSIRxx7ESLNv?p=preview
Thank you for the great tutorial. I have a problem that after few hours the web server stops responding. The loop is still runing but no web. I read some sources that it is needed to call client.stop() but they use Wifiserver and wifi.h. I am not sure for WebServer object.
here also you can use client.stop() at end.