Beginning guide to JSON Javascript AJAX Webserver with ESP8266

Today in this tutorial I will show you a beginning guide to JSON Javascript AJAX Webserver with ESP8266 step by step complete project.


≡ Required Component :


Here is a list of the hardware we remanent   Beginning guide to JSON Javascript AJAX Webserver with ESP8266

  1. NodeMcu8266
  2. Breadboard
  3. Connecting wire
  4. Breadboard Power Supply Module

≡ JSON


JSON (JavaScript Object Notation) is a lightweight data-interchange format.  simple for humans to read and write. accessible for machines to parse and generate. It is based on a subset of the JavaScript Programming Language. JSON is a text format that is simply language independent but uses conventions that are easy to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.


≡ JSON Encode Example


For this program, the ArduinoJSON library is needed. Go to Sketch>>Include Library>>Manage Libraries. Then search for JSON and Install library Arduinojson by Benoit Blanchon 

This example explains how to encode Analog and digital value with an example of the ADC and Flash button.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ArduinoJson.h>
const char* wifiName = "Wi-Fi-name";
const char* wifiPass = "Wi-Fi-password";
ESP8266WebServer server(80);  //Define server object
//Handles http request
void handleRoot() {
  String webPage;
  // Allocate JsonBuffer
  // Use arduinojson.org/assistant to compute the capacity.
  StaticJsonBuffer<500> jsonBuffer;
  // Create the root object
  JsonObject& root = jsonBuffer.createObject();
  root[" Read ADC Pin Value"] = analogRead(A0); //Put Sensor value
  root["Read Digital Pin Value"] = digitalRead(0); //Reads Flash Button Status
  root.printTo(webPage);  //Store JSON in String variable
  server.send(200, "text/html", webPage);
}
// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.print("Connecting");
  WiFi.begin(wifiName, wifiPass);   //Connect to Wi-Fi
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wi-Fi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());   //You can get IP address assigned to ESP
  server.on("/", handleRoot);      //Associate handler function to web requests
  server.begin(); //Start web server
  Serial.println("HTTP server started");
}
void loop() {
  //Handle Clinet requests
  server.handleClient();
}

After uploading get the IP of NodeMCU from your  Serial monitor. Open the web browser and access IP. Press/Release flash button and refresh the webpage to examine updated values in JSON.

JSON Encode Results
JSON Encode Results

≡ Java Scripts


javaScript is a programming language that attaches interactivity to your website (for example games, responses when buttons pressed or data entered in forms, dynamic styling, and animation). JavaScript (“JS” for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites. It invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation.


≡ JavaScript Example


In this example, we make a complete paddle ball game using JavaScripts. Fist create htmlPage.h header file.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Gamedev Canvas Workshop - lesson 10: finishing up</title>
    <style>* { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; }</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var ballRadius = 10;
    var x = canvas.width/2;
    var y = canvas.height-30;
    var dx = 2;
    var dy = -2;
    var paddleHeight = 10;
    var paddleWidth = 75;
    var paddleX = (canvas.width-paddleWidth)/2;
    var rightPressed = false;
    var leftPressed = false;
    var brickRowCount = 5;
    var brickColumnCount = 3;
    var brickWidth = 75;
    var brickHeight = 20;
    var brickPadding = 10;
    var brickOffsetTop = 30;
    var brickOffsetLeft = 30;
    var score = 0;
    var lives = 3;
    var bricks = [];
    for(var c=0; c<brickColumnCount; c++) {
        bricks[c] = [];
        for(var r=0; r<brickRowCount; r++) {
            bricks[c][r] = { x: 0, y: 0, status: 1 };
        }
    }
    document.addEventListener("keydown", keyDownHandler, false);
    document.addEventListener("keyup", keyUpHandler, false);
    document.addEventListener("mousemove", mouseMoveHandler, false);
    function keyDownHandler(e) {
        if(e.keyCode == 39) {
            rightPressed = true;
        }
        else if(e.keyCode == 37) {
            leftPressed = true;
        }
    }
    function keyUpHandler(e) {
        if(e.keyCode == 39) {
            rightPressed = false;
        }
        else if(e.keyCode == 37) {
            leftPressed = false;
        }
    }
    function mouseMoveHandler(e) {
        var relativeX = e.clientX - canvas.offsetLeft;
        if(relativeX > 0 && relativeX < canvas.width) {
            paddleX = relativeX - paddleWidth/2;
        }
    }
    function collisionDetection() {
        for(var c=0; c<brickColumnCount; c++) {
            for(var r=0; r<brickRowCount; r++) {
                var b = bricks[c][r];
                if(b.status == 1) {
                    if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
                        dy = -dy;
                        b.status = 0;
                        score++;
                        if(score == brickRowCount*brickColumnCount) {
                            alert("YOU WIN, CONGRATS!");
                            document.location.reload();
                        }
                    }
                }
            }
        }
    }
    function drawBall() {
        ctx.beginPath();
        ctx.arc(x, y, ballRadius, 0, Math.PI*2);
        ctx.fillStyle = "#0095DD";
        ctx.fill();
        ctx.closePath();
    }
    function drawPaddle() {
        ctx.beginPath();
        ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
        ctx.fillStyle = "#0095DD";
        ctx.fill();
        ctx.closePath();
    }
    function drawBricks() {
        for(var c=0; c<brickColumnCount; c++) {
            for(var r=0; r<brickRowCount; r++) {
                if(bricks[c][r].status == 1) {
                    var brickX = (r*(brickWidth+brickPadding))+brickOffsetLeft;
                    var brickY = (c*(brickHeight+brickPadding))+brickOffsetTop;
                    bricks[c][r].x = brickX;
                    bricks[c][r].y = brickY;
                    ctx.beginPath();
                    ctx.rect(brickX, brickY, brickWidth, brickHeight);
                    ctx.fillStyle = "#0095DD";
                    ctx.fill();
                    ctx.closePath();
                }
            }
        }
    }
    function drawScore() {
        ctx.font = "16px Arial";
        ctx.fillStyle = "#0095DD";
        ctx.fillText("Score: "+score, 8, 20);
    }
    function drawLives() {
        ctx.font = "16px Arial";
        ctx.fillStyle = "#0095DD";
        ctx.fillText("Lives: "+lives, canvas.width-65, 20);
    }
    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        drawBricks();
        drawBall();
        drawPaddle();
        drawScore();
        drawLives();
        collisionDetection();
        if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
            dx = -dx;
        }
        if(y + dy < ballRadius) {
            dy = -dy;
        }
        else if(y + dy > canvas.height-ballRadius) {
            if(x > paddleX && x < paddleX + paddleWidth) {
                dy = -dy;
            }
            else {
                lives--;
                if(!lives) {
                    alert("GAME OVER");
                    document.location.reload();
                }
                else {
                    x = canvas.width/2;
                    y = canvas.height-30;
                    dx = 3;
                    dy = -3;
                    paddleX = (canvas.width-paddleWidth)/2;
                }
            }
        }
        if(rightPressed && paddleX < canvas.width-paddleWidth) {
            paddleX += 7;
        }
        else if(leftPressed && paddleX > 0) {
            paddleX -= 7;
        }
        x += dx;        y += dy;
       requestAnimationFrame(draw);
    }
    draw();
</script>
</body>
</html>

The program built using two parts first is htmlPage.h contains all web pages and JavaScript’s and NodeMCU code works web server and Wi-Fi. JavaScript executed on the client-side so NodeMCU just sends Java Script code to the Web browser.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "htmlPage.h" //Our HTML JavaScript Web page
const char* wifiName = "Wi-Fi-name";
const char* wifiPass = "Wi-Fi-password";
ESP8266WebServer server(80);  //Define server object
//Handles http request
void handleRoot() {
  server.send(200, "text/html", webPage);  //webPage is defined in htmlPage.h file
}
void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(2,OUTPUT);
  Serial.println();
  Serial.print("Connecting");
  WiFi.begin(wifiName, wifiPass);   //Connect to Wi-Fi
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wi-Fi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());   //You can get IP address assigned to ESP
  server.on("/", handleRoot);      //Associate handler function to web requests
  server.begin(); //Start web server
  Serial.println("HTTP server started");
}
void loop() {
  //Handle Clinet requests
  server.handleClient();
}

Open the serial monitor and get the IP address assigned NodeMCU. Open the same IP in a web browser. Paddleball game opens and you can play with mouse or keyboard. By javascript, you can attach gauges, graphs, and dynamic functionality to your IoT webpage.

JavaScript Web Server
JavaScript Web Server

≡ AJAX


AJAX stands for Asynchronous JavaScript and XML. The AJAX is the most advanced technique for building better, faster, and more interactive web applications with the help of XML, HTML, CSS, and JavaScript. AJAX is a way of creating fast and dynamic web pages.

AJAX allows web pages to modernized asynchronously by exchanging little 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.


≡ AJAX Example


In this example, we establish an easy LED on/off and ADC value display in real-time. This way both receiving data from ESP8266 and Sending data to ESP8266 can be displayed.

const char webPage[] 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 repetitively 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="mechatronicslab.net">mechatronicslab.net/a>
</body>
</html>
)=====";

Save header file at the same location where .ino file is

Open the serial monitor and see the IP address assigned to NodeMCU. Open the same IP in a web browser.  Press on-off buttons and see the onboard LED.

AJAX Web Page
AJAX Web Page

Visit to get more tutorials on ESP8266

 593 total views,  3 views today