ESP8266 jQuery and AJAX Web Server

This example shows how to use jQuery in ESP8266, NodeMCU ? There are two ways to use jQuery in ESP8266 Web Sever, first is to use cdn server and second is directly putting jQuery on ESP Flash File System. We will look into both examples. We make use of jQuery Knob to demonstrate real time fading of LED control using jQuery and AJAX requests.

What is jQuery ?

jQuery is not a language, but it is a well written JavaScript code. As quoted on official jQuery website, “it is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development”.

What is Ajax and jQuery?

With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post – And you can load the external data directly into the selected HTML elements of your web page! Without jQuery, AJAX coding can be a bit tricky!

Example 1: NodeMCU Using jQuery from CDN server

In this example we use CDN server to get jQuery file. Disadvantage of this method is we need active internet connection to the WiFi Hot spot.

/*
 * ESP8266 NodeMCU jQuery CDN Demo
 * 
 * https://circuits4you.com
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

//ESP Web Server Library to host a web page
#include <ESP8266WebServer.h>

//---------------------------------------------------------------
//Our HTML webpage contents in program memory
const char MAIN_page[] PROGMEM = R"=====(
  <!DOCTYPE html>
  <html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
      $("p").click(function(){
          $(this).hide();
      });
  });
  </script>
  </head>
  <body>
  
  <p>If you click on me, I will disappear.</p>
  <p>Click me away!</p>
  <p>Click me too!</p>
  <br><hr>
  <a href="https://circuits4you.com">circuits4you.com</a>  
  </body>
  </html>
)=====";
//---------------------------------------------------------------

//On board LED Connected to GPIO2
#define LED 2  

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

//Declare a global object variable from the ESP8266WebServer class.
ESP8266WebServer server(80); //Server on port 80

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
 Serial.println("You called root page");
 String s = MAIN_page; //Read HTML contents
 server.send(200, "text/html", s); //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); 

  //Power on LED state off
  digitalWrite(LED,HIGH);
  
  WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only
  
  WiFi.begin(ssid, password);

  // 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.begin();                  //Start server
  Serial.println("HTTP server started");
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void){
  server.handleClient();          //Handle client requests
}

Open serial monitor and get the ip address and enter ip in web browser.

Example 2: ESP8266 Web Server with jQuery and AJAX

In this example we load our web page, jQuery and other java Scripts directly on the ESP Flash File System. Read more on SPIFFS

/*
 * ESP8266 SPIFFS HTML Web Page with JPEG, PNG Image 
 * https://circuits4you.com
 */

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <FS.h>   //Include File System Headers

const char* htmlfile = "/index.html";

//WiFi Connection configuration
const char *ssid = "circuits4you.com";
const char *password = "password";

#define LED 2

ESP8266WebServer server(80);


void handlePWM(){
  String PWM = server.arg("pwm");
  int p = 1024 - (PWM.toInt())*10;
  Serial.println(p);
  analogWrite(LED,p);
  server.send(200, "text/plane","");
}

void handleRoot(){
  server.sendHeader("Location", "/index.html",true);   //Redirect to our html web page
  server.send(302, "text/plane","");
}

void handleWebRequests(){
  if(loadFromSpiffs(server.uri())) return;
  String message = "File Not Detected\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " NAME:"+server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  Serial.println(message);
}

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();

  pinMode(LED,OUTPUT);
  //Initialize File System
  SPIFFS.begin();
  Serial.println("File System Initialized");

  
  //Connect to wifi Network
  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(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  //Initialize Webserver
  server.on("/",handleRoot);
  server.on("/setLED",handlePWM); //Reads ADC function is called from out index.html
  server.onNotFound(handleWebRequests); //Set setver all paths are not found so we can handle as per URI
  server.begin();  
}

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

bool loadFromSpiffs(String path){
  String dataType = "text/plain";
  if(path.endsWith("/")) path += "index.htm";

  if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
  else if(path.endsWith(".html")) dataType = "text/html";
  else if(path.endsWith(".htm")) dataType = "text/html";
  else if(path.endsWith(".css")) dataType = "text/css";
  else if(path.endsWith(".js")) dataType = "application/javascript";
  else if(path.endsWith(".png")) dataType = "image/png";
  else if(path.endsWith(".gif")) dataType = "image/gif";
  else if(path.endsWith(".jpg")) dataType = "image/jpeg";
  else if(path.endsWith(".ico")) dataType = "image/x-icon";
  else if(path.endsWith(".xml")) dataType = "text/xml";
  else if(path.endsWith(".pdf")) dataType = "application/pdf";
  else if(path.endsWith(".zip")) dataType = "application/zip";
  File dataFile = SPIFFS.open(path.c_str(), "r");
  if (server.hasArg("download")) dataType = "application/octet-stream";
  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
  }

  dataFile.close();
  return true;
}

Upload this code after that you have to upload your SPIFFS FLASH data

How to upload flash data?

  • Step 1: PWM_ESP8266_Ajax_Demo
  • Step 2: Put these files in data folder and this folder must be near to your .ino file
  • Step 3: Upload SPIFF using Arduino IDE ESP8266 Sketch Data Upload 

After uploading all you code and Web Pages, jQuery its time to test, get ip from serial monitor and open it in web browser.NodeMCU jQuery AJAX Example

Rotate the knob and observer on board LED Fading.

Related Notes:

  1. AJAX demo bi-direction communication
  2. Using analog gauge to display adc value in real time
  3. SPIFFS File System

 

 

2 thoughts on “ESP8266 jQuery and AJAX Web Server

Leave a Reply