ESP32 Asynchronous Web Server – jQuery AJAX

AJAX lets a web page exchange data with a server and update individual parts of the page without reloading everything. In jQuery, the ajax() method provides the core AJAX functionality.

Difficulty: Intermediate

Created: February 2023

Reviewed: September 2026

Development board: ESP32 Dev Module

We will first work through the original jQuery/AJAX example, reading an LDR light sensor and switching an LED with a button. Then we will build the same project with current libraries and LittleFS.

The original example uses the SPIFFS file system. For new projects, Espressif recommends LittleFS or FFat, although SPIFFS can still be used.

The original example with SPIFFS

In the original SPIFFS example, we extend the ESP32 Web Updater and SPIFFS file manager project.

Build the circuit

We will use the circuit below for both examples.

Connect an LED to ESP32 GPIO4 through a 330 Ω series resistor. Following the diagram, connect an LDR and a 10 kΩ resistor as a voltage divider to GPIO36. The two ends of the divider connect to 3.3 V and GND.

ESP32 wiring: LED on GPIO4 and an LDR with a 10 kΩ voltage divider on GPIO36, connected to 3.3 V and GND
Connecting the LED and LDR to the ESP32. We will use the same circuit in the next example.

Download, installation and first steps

Download the project files here.

Extract the downloaded project and open the sketch in the Arduino IDE. Enter your Wi-Fi network name and password in config.h, and change the web login credentials.

Warning: Change the default admin/admin credentials before uploading the sketch, and use this example only on a trusted local network.

const char* ssid = "SSID";
const char* password = "Password";

const char* http_username = "admin";
const char* http_password = "admin";

const char* host = "esp32-asyncwebserver";

...

In config.h, specify the name of the uploaded jQuery file, including the leading slash. The LDR and LED pins and their state variables are also defined here.

...

const char* jquery = "/jquery-3.6.3.min.js";

const char ldrPin = 36;
String sensorValue = "0";

const char ledPin = 4;
String ledValue = "true";

If SPIFFS cannot be mounted on first use, it may not yet be initialized on your ESP32. Setting FORMAT_SPIFFS_IF_FAILED to true allows it to be formatted when mounting fails. Formatting erases any files already stored there.

#define FORMAT_SPIFFS_IF_FAILED true

After SPIFFS mounts successfully, set the macro back to false. Otherwise a later mount failure could trigger formatting and erase stored data.

#define FORMAT_SPIFFS_IF_FAILED false

Then upload the sketch to the ESP32.

Open http://esp32-asyncwebserver.local/manager in your browser and sign in with the username and password you entered in config.h.

In the file manager, upload jquery-3.6.3.min.js and index.html from the project folder.

SPIFFS file manager: uploading index.html and the local jQuery file
Uploading index.html and the jQuery file through the file manager.

If the esp32-asyncwebserver.local address does not work, use the ESP32 IP address shown in the Serial Monitor.

How does the code work?

In loop(), we read the LDR once per second. With an asynchronous web server, it is better to avoid blocking delays. This section uses millis() for timing, so no delay() call is needed.

Millis = millis();
if (Millis - previousMillis >= 1000) 
{
   previousMillis = Millis;
   sensorValue = String(analogRead(ldrPin));
}

The following routes handle browser requests. They serve the uploaded index.html and jQuery files, return the sensor and LED states, and receive the request to switch the LED.

/**********   Added server.on routes start here...  ***********/

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
  {
    request->send(SPIFFS, "/index.html", "text/html", false, processor);
  });

  server.on(jquery, HTTP_GET, [](AsyncWebServerRequest *request)
  {
    request->send(SPIFFS, jquery, "text/javascript");
  });

  server.on("/sensorvalue", HTTP_GET, [](AsyncWebServerRequest *request)
  {
    request->send(200, "text/text", sensorValue);
  });

  server.on("/ledvalue", HTTP_GET, [](AsyncWebServerRequest *request)
  {
    request->send(200, "text/text", ledValue);
  });


  server.on("/ledswitch", HTTP_POST, [](AsyncWebServerRequest *request)
  {
    ledValue = request->getParam(0)->value();

    if(ledValue == "true")
    {
      ledValue = "false";
      digitalWrite(ledPin, LOW);
    }
    else if(ledValue == "false")
    {
      ledValue = "true";
      digitalWrite(ledPin, HIGH);
    }
    request->send(200);
  });

  /***************  Added server.on routes end here *******************/

The server.on("/", HTTP_GET, ...) route serves the uploaded index.html home page.

The server.on(jquery, HTTP_GET, ...) route returns the jQuery file referenced in the home page’s head section.

<!DOCTYPE html>
<html>
    <head>
        <title>ESP32 asyncWebserver-jQuery-ajax</title>
        <script src="jquery-3.6.3.min.js"></script>
.....

We put the JavaScript inside jQuery’s ready() handler so the page elements are available when the script starts using them.

<script>
  $(document).ready(function() {
    ....
</script>

The /sensorvalue route returns the current LDR reading. In the browser, setInterval() sends a jQuery $.get() request to that route once per second and updates the displayed value from the response.

setInterval(function () {
  $.get("/sensorvalue", function(data){
    $('#sensor_result').html(data);
  });
},1000);

The received data goes into the element with the ID sensor_result, so the value changes without reloading the page.

<div id="sensor_result" style="height:40px;"></div>

The /ledvalue route returns the LED state. The browser stores it in a hidden HTML element and changes the button label accordingly.

$.get("ledvalue", function(data) {
  $('#led_status').val(data);
});
					
var str = $("#led_status").val();
				
if(str == "true") {
  $("#ledswitch_button").text("Turn on the led!");
}
else {
  $("#ledswitch_button").text("Turn off the led!!");
}

When we press the button, jQuery’s click() handler reads the LED state from the hidden element, updates the label and sends a $.post() request to the server. It then requests the state again with $.get() and stores the response in the hidden element.

$("#ledswitch_button").click(function() {
  str = $("#led_status").val();
					
  if(str == "true") {
    $("#ledswitch_button").text("Turn on the led!");
  }
  else {
    $("#ledswitch_button").text("Turn off the led!");
  }
  $.post("ledswitch", {
    led: str
  });
  $.get("ledvalue", function(data) {
    $('#led_status').val(data);
  });
});

The /ledswitch POST route receives the button request. This is where we turn the LED on or off and update its state variable.

Here is the key idea once more: the browser uses regular GET requests to read the LDR and a POST request to switch the LED. The page does not need to reload.

What has changed since then?

The original example has shown us how to read the LDR and switch an LED with jQuery/AJAX.

The ESP32 libraries and Arduino environment have developed since then. We will now implement the same idea with LittleFS and jQuery 4.0.0. The wiring stays the same: the LDR remains on GPIO36 and the LED on GPIO4.

Today, we could also do this without jQuery by using the browser’s built-in Fetch API. Here we keep jQuery/AJAX because that is what we want to understand.

The jQuery/AJAX example with LittleFS

We keep the circuit from the original example: the LED is on GPIO4, and the LDR voltage divider is on GPIO36. We tested the project in both mobile and desktop browsers.

Download the project and get started

Download the project with the button below.

Project structure and local files. The files to be uploaded to the ESP32’s LittleFS file system belong in the data/ folder.

esp32-async-webserver-jquery-ajax-en-v2-project/
├── esp32-async-webserver-jquery-ajax-en-v2-project.ino
├── config.h
└── data/
    ├── index.html
    └── jquery-4.0.0.min.js

After downloading, extract esp32-async-webserver-jquery-ajax-en-v2-project.zip into your Arduino projects folder.

Then enter your Wi-Fi credentials in config.h. If you want to use different GPIO pins, you can change them there too. Do not share this file with others.

#pragma once
constexpr char WIFI_SSID[] = "YOUR_WIFI_SSID";
constexpr char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";
constexpr uint8_t LED_PIN = 4;
constexpr uint8_t LDR_PIN = 36;

If they are not already installed, install the Arduino-ESP32 platform and the ESPAsyncWebServer and AsyncTCP libraries.

For the hardware test, we used Arduino-ESP32 3.3.12, ESPAsyncWebServer 3.12.1 and AsyncTCP 3.5.0.

Uploading the LittleFS file system

The website files are in the data/ folder. index.html is the web page, while jquery-4.0.0.min.js is the locally stored copy of jQuery.

These files are not transferred to the ESP32 when we upload the sketch in the usual way. We must create a separate LittleFS file-system image from the contents of data/ and upload it.

In the Windows environment we tested, we used the LittleFS Filesystem Uploader 1.6.3 extension. Download the VSIX file for that release, copy it to C:\Users\<username>\.arduinoIDE\plugins\, and restart the Arduino IDE. Create the plugins folder if it does not exist. On other operating systems, follow the extension’s installation guide.

Open the downloaded project’s sketch in the Arduino IDE. Check that both files are in the adjacent data/ folder. Select the ESP32 Dev Module board and the correct serial port, then close the Serial Monitor so it does not occupy the port.

Open the Arduino IDE Command Palette with Ctrl+Shift+P and run Upload LittleFS to Pico/ESP8266/ESP32. Wait until the upload finishes without errors. This places index.html and the local jQuery file in the ESP32’s LittleFS file system.

Upload and run the sketch

Next, compile and upload the sketch in the usual way from the Arduino IDE. Open the Serial Monitor at 115200 baud and check the Wi-Fi connection, the device’s IP address and the HTTP server startup message.

Open the local address printed by the ESP32 in your browser. If you see the LDR reading and the two LED buttons, try switching the LED and changing the amount of light reaching the sensor.

Try this example only on a trusted local network. The web page uses HTTP and does not provide internet-grade authentication, so do not expose the ESP32 directly to the public internet.

How does the code work?

The data/ folder contains the web page (index.html) and the complete jquery-4.0.0.min.js file. The ESP32 stores both in LittleFS. The browser therefore receives jQuery from the ESP32 rather than an external CDN, so the example can work on the local network without internet access.

At the beginning of the sketch, we include the required libraries. WiFi.h handles the network connection, and LittleFS provides the file system. ESPAsyncWebServer answers browser requests, while AsyncTCP supports the network connection. config.h contains the Wi-Fi credentials and GPIO pin definitions.

#include <Arduino.h>
#include <WiFi.h>
#include <LittleFS.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "config.h"

We create an instance of the asynchronous web server class.

AsyncWebServer server(80);

Now let’s connect to the Wi-Fi network.

void connectWiFi()
{
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");

  const unsigned long started = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - started < WIFI_TIMEOUT_MS)
  {
    delay(250);
    Serial.print('.');
  }

  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.println("\nWi-Fi connection timed out; restarting in 5 seconds.");
    delay(5000);
    ESP.restart();
  }

  Serial.printf("\nConnected. Open http://%s/\n", WiFi.localIP().toString().c_str());
}

In station mode (WIFI_STA), the ESP32 tries to join the configured Wi-Fi network for up to twenty seconds. If it cannot connect, it waits another five seconds and restarts.

On success, it prints the device’s IP address to the Serial Monitor.

In setup(), we start the serial connection, configure the LED pin as an output and the LDR pin as an input, and initially turn the LED off.

void setup()
{
  Serial.begin(115200);

  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);
  pinMode(LDR_PIN, INPUT);

Next, the ESP32 tries to mount its LittleFS storage. If this fails, it prints an error message to the Serial Monitor.

After a successful mount, the sketch checks for index.html and the required jquery-4.0.0.min.js file. If either is missing, it also reports that in the Serial Monitor.

  if (!LittleFS.begin(false))
  {
    Serial.println("LittleFS mount failed. No automatic formatting was attempted.");
    return;
  }

  if (!LittleFS.exists("/index.html"))
  {
    Serial.println("ERROR: /index.html is missing from LittleFS.");
  }  
  if (!LittleFS.exists("/jquery-4.0.0.min.js"))
  {
    Serial.println("ERROR: /jquery-4.0.0.min.js is missing from LittleFS.");
  }

Then we initiate the Wi-Fi connection.

connectWiFi();

Once connected, we register the web server routes.

For requests under the root path, the server automatically serves files from LittleFS. If no file name is given, it loads index.html.

server.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");

When the browser opens index.html, it immediately requests the current status.

function refreshStatus() {
  $.ajax({ url: '/api/status', method: 'GET', dataType: 'json', cache: false })
    .done(renderStatus)
    .fail(showFailure);
}

refreshStatus();
window.setInterval(refreshStatus, 1000);

The ESP32 web server receives this request on GET /api/status.

server.on("/api/status", HTTP_GET, [](AsyncWebServerRequest *request)
{
  sendStatus(request);
});

sendStatus() returns the JSON response assembled by statusJson().

void sendStatus(AsyncWebServerRequest *request)
{
  request->send(200, "application/json", statusJson());
}

In statusJson(), the ESP32 reads the LDR voltage divider on GPIO36 with analogRead(). It returns the numeric ldr value and the LED’s Boolean led state together as JSON.

String statusJson()
{
  const int ldrValue = analogRead(LDR_PIN);
  const bool ledOn = digitalRead(LED_PIN) == HIGH;
  return String("{\"ldr\":") + ldrValue + ",\"led\":" + (ledOn ? "true" : "false") + "}";
}

In the browser, index.html receives the JSON response through jQuery’s $.ajax(). The .text() calls update only the visible LDR and LED values, without reloading the whole page.

function renderStatus(data) {
      $('#ldr-value').text(data.ldr);
      $('#led-state').text(data.led ? 'on' : 'off');
      $('#message').removeClass('error').text('Updated without reloading the page.');
}

When a button is pressed, the browser sends a POST request to /api/led with state=on or state=off. It then updates the LED status text from the server’s response.

$('button[data-state]').on('click', function () {
  $.ajax({
    url: '/api/led',
    method: 'POST',
    data: { state: $(this).data('state') },
    dataType: 'json'
  }).done(renderStatus).fail(showFailure);
});

The ESP32 web server expects a parameter named state in the request body. If it is missing, the server returns HTTP 400. If its value is neither on nor off, it returns HTTP 422. Otherwise it switches the LED on GPIO4 and responds with the updated status.

server.on("/api/led", HTTP_POST, [](AsyncWebServerRequest *request)
{
  if (!request->hasParam("state", true)) {
    request->send(400, "application/json", "{\"error\":\"missing state\"}");
    return;
  }
  const String state = request->getParam("state", true)->value();
  if (state != "on" && state != "off") {
    request->send(422, "application/json", "{\"error\":\"invalid state\"}");
    return;
  }
  digitalWrite(LED_PIN, state == "on" ? HIGH : LOW);
  sendStatus(request);
});

In the browser, setInterval(refreshStatus, 1000) calls refreshStatus() every second and updates the LDR and LED status text.

If someone requests a page that does not exist, server.onNotFound() returns the plain text “Not found” with HTTP status 404.

  server.onNotFound([](AsyncWebServerRequest *request)
  {
    request->send(404, "text/plain", "Not found");
  });

Finally, we start the asynchronous web server.

  server.begin();
  Serial.println("HTTP server started.");

Try it out

Open the page on a phone and a computer. In our test, switching the LED in either browser caused the other browser to show the new state shortly afterward.

The server does not push this change to the clients. Each open page notices it through its own AJAX request once per second.

Modern ESP32 jQuery/AJAX page with the LED on and the raw LDR reading
The web page with the LED on and the current LDR reading.
Modern ESP32 jQuery/AJAX page with the LED off and the raw LDR reading
After switching off the LED, the displayed state changes too.

Troubleshooting

Serial port in use: Close the Serial Monitor before uploading LittleFS. If No port specified, check IDE menus. still appears even though you selected the right port and closed the monitor, restart the Arduino IDE. Select the ESP32 board and port again, then retry. That solved the issue in our test. Other port problems may need further investigation.

LittleFS mount failed: In normal use, the sketch calls LittleFS.begin(false), so it does not automatically format the file system after a mount failure. If an older, damaged or incompatible file system is present, a one-time recovery option is LittleFS.begin(true). Use it only if you understand the consequence: a failed mount may trigger formatting and erase stored files. Back up important data first. After recovery, restore false and upload the files from data/ again.

HTML or jQuery file missing: Check that data/ contains both index.html and jquery-4.0.0.min.js. If the Serial Monitor reports a missing file, upload the complete LittleFS image again. Uploading the sketch alone does not restore the web page files.

Comparing the original and new versions

Both versions teach the same idea: the ESP32 responds to browser requests, while we read the LDR and switch the LED without reloading the whole page.

The main difference is how the web page is stored and served, and which libraries we use. The original program uses SPIFFS and a local copy of jQuery 3.6.3; we upload its files with the older project’s file manager.

In the new version, we upload the web page separately to LittleFS. Arduino-ESP32 3.3.12, ESPAsyncWebServer 3.12.1, AsyncTCP 3.5.0 and a local copy of jQuery 4.0.0 make up the tested environment. The browser refreshes the LDR reading on GPIO36 and the LED state on GPIO4 with AJAX requests every second. It worked on both phone and computer: when we switched the LED in one browser, the other followed the state change.


← Further Arduino tutorials

← More Arduino / ESP Examples and Projects