ESP8266 (ajax) update part of web page without refreshing

In this tutorial we receive ADC data and send LED on off data to ESP8266 without refreshing webpage. 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 NodeMCU, Laptop and USB cable

What you will learn?

  1. ESP8266 Ajax web page update without refresh.
  2. Sending data to ESP NodeMCU without page refresh.
  3. Getting data from ESP8266 NodeMCU 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 NodeMCU AJAX Works ?

In ESP8266 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

ESP ajax example

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>
<body>

<div id="demo">
<h1>The ESP8266 NodeMCU Update web page without refresh</h1>
	<button type="button" onclick="sendData(1)">LED ON</button>
	<button type="button" onclick="sendData(0)">LED OFF</button><BR>
</div>

<div>
	ADC Value is : <span id="ADCValue">0</span><br>
    LED State is : <span id="LEDState">NA</span>
</div>
<script>
function sendData(led) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("LEDState").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "setLED?LEDstate="+led, true);
  xhttp.send();
}

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>
<br><br><a href="https://circuits4you.com">Circuits4you.com</a>
</body>
</html>
)=====";

ESP8266 NodeMCU Main INO file Code

/*
 * ESP8266 NodeMCU AJAX Demo
 * Updates and Gets data from webpage without page refresh
 * https://circuits4you.com
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

#include "index.h" //Our HTML webpage contents with javascripts

#define LED 2  //On board LED

//SSID and Password of your WiFi router
const char* ssid = "circuits4you.com";
const char* password = "123456789";

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
}

void handleADC() {
 int a = analogRead(A0);
 String adcValue = String(a);
 
 server.send(200, "text/plane", adcValue); //Send ADC value only to client ajax request
}

void handleLED() {
 String ledState = "OFF";
 String t_state = server.arg("LEDstate"); //Refer  xhttp.open("GET", "setLED?LEDstate="+led, true);
 Serial.println(t_state);
 if(t_state == "1")
 {
  digitalWrite(LED,LOW); //LED ON
  ledState = "ON"; //Feedback parameter
 }
 else
 {
  digitalWrite(LED,HIGH); //LED OFF
  ledState = "OFF"; //Feedback parameter  
 }
 
 server.send(200, "text/plane", ledState); //Send web page
}
//==============================================================
//                  SETUP
//==============================================================
void setup(void){
  Serial.begin(115200);
  
  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  //Onboard LED port Direction output
  pinMode(LED,OUTPUT); 
  
  // 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(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
 
  server.on("/", handleRoot);      //Which routine to handle at root location. This is display page
  server.on("/setLED", handleLED);
  server.on("/readADC", handleADC);

  server.begin();                  //Start server
  Serial.println("HTTP server started");
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void){
  server.handleClient();          //Handle client requests
}

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.

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

  1. SPIFFS (ESP File System) to load webpages in Flash memory
  2. Upload images in ESP8266 and display it in web page
  3. Using jQuery advance web server on ESP8266

ResultsNodeMCU Ajax javascript Example

References:

To get more information on all types of web and communication protocols used with Node MCU, Read my eBook NodeMCU: Communication methods and protocols.

 

6 thoughts on “ESP8266 (ajax) update part of web page without refreshing

  1. hello, and thank you verrrrry much.
    i have implemented these codes successfully .
    but how can i have two clients and one esp8266 server with this program?
    which parts should be implemented on server and clients?

  2. If i try to add more function getData() functions , the entire code goes mad , its displays everything everywhere. For example , i tryed to print to the website an uptime counter , and a name tagged to an rfid , i have function getData() for the name and the uptime too. But in the web the uptime goes to the name’s place. Maybe it is because the multiple ” function getData() {}. How can i solve this problem?

  3. Hello, i am having some troubles on my code. I would like to build a wifi thermostat ( temperature controller ) using nodemcu lolin esp8266 12e and i can’t build the following scenario: when i click a button i want that Tref1 to decrese by 0.5 and when i click another button, to rise 0.5. it is like a button without feedback parameter.

    html code:

    P1 0 – 6
    +
    NA

    function getDataTref1() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById(“Tref1Value”).innerHTML =
    this.responseText;
    }
    };
    xhttp.open(“GET”, “readTref1”, true);
    xhttp.send();
    }

    Arduino code:

    void handleRoot() {
    String s = MAIN_page; //Read HTML contents
    server.send(200, “text/html”, s); //Send web page
    }

    void handleTref1() {
    float b = Tref1;
    String Tref1value = String(b);

    server.send(200, “text/plane”, Tref1value); //Send Tref1 value only to client ajax request
    }

Leave a Reply