AJAX - Real-Time Updates using AJAX and alternatives like WebSockets.

1) What Are Real-Time Updates?

  • Real-time updates allow web pages to reflect changes instantly without requiring the user to manually refresh the page.

  • Common use cases: chat apps, stock tickers, live notifications, collaborative editing.


2) Using AJAX for Real-Time Updates

a) AJAX Polling

  • Browser repeatedly sends AJAX requests at regular intervals to check for updates.

  • Example: every 5 seconds, check if new messages are available.

Example:

function fetchMessages() {
  fetch("/api/messages")
    .then(res => res.json())
    .then(data => {
      // Update the message list
      const chat = document.getElementById("chat");
      chat.innerHTML = data.map(m => `<p>${m.text}</p>`).join("");
    })
    .catch(err => console.error(err));
}

// Poll every 5 seconds
setInterval(fetchMessages, 5000);

Pros:

  • Simple to implement.

  • Works in all browsers.

Cons:

  • Inefficient → requests are made even if no new data exists.

  • Can increase server load if many clients poll frequently.


b) Long Polling

  • Server holds the request open until new data is available (or timeout occurs).

  • Once data is sent, client immediately opens a new request.

  • Reduces unnecessary requests compared to simple polling.

Example:

function longPoll() {
  fetch("/api/messages")
    .then(res => res.json())
    .then(data => {
      // Update UI
      document.getElementById("chat").innerHTML = data.map(m => `<p>${m.text}</p>`).join("");
      // Immediately poll again
      longPoll();
    })
    .catch(err => setTimeout(longPoll, 5000)); // Retry on error
}

longPoll();

Pros:

  • More efficient than standard polling.
    Cons:

  • Still HTTP overhead.

  • Latency depends on server timeout settings.


3) Alternatives to AJAX for Real-Time

a) WebSockets

  • Full-duplex communication channel between browser and server.

  • Server can push updates instantly without the client polling.

Example with WebSocket:

const socket = new WebSocket("wss://example.com/chat");

socket.onmessage = function(event) {
  const chat = document.getElementById("chat");
  chat.innerHTML += `<p>${event.data}</p>`;
};

socket.onopen = () => console.log("Connected to server");

Pros:

  • True real-time updates.

  • Low overhead after connection is established.

  • Supports bidirectional communication (client ↔ server).

Cons:

  • Requires server-side WebSocket support.

  • More complex than simple AJAX.


b) Server-Sent Events (SSE)

  • Server can push events to the client over a single HTTP connection.

  • Browser listens for events using EventSource.

Example:

const source = new EventSource("/events");

source.onmessage = function(event) {
  document.getElementById("notifications").innerHTML += `<p>${event.data}</p>`;
};

Pros:

  • Simple, one-way updates.

  • Lightweight alternative to WebSockets for server → client.

Cons:

  • Only server → client (no bidirectional).

  • Limited browser support compared to WebSockets.


4) Comparison Table

Method Direction Efficiency Complexity Use Case
AJAX Polling Client → Server Low Simple Small apps, low traffic
AJAX Long Polling Client → Server Medium Medium Moderate real-time needs
Server-Sent Events Server → Client High Simple Notifications, feeds
WebSockets Bi-directional High Medium Chat, collaboration, games

5) Best Practices for Real-Time AJAX

  • Use long polling or WebSockets instead of frequent polling for performance.

  • Implement debouncing or throttling if polling is unavoidable.

  • Use JSON for lightweight data transfer.

  • Ensure HTTPS/WSS for secure communication.

  • Consider reconnect logic for network failures.


Summary

  • AJAX Polling: simplest but inefficient.

  • Long Polling: reduces unnecessary requests.

  • SSE: lightweight server → client push.

  • WebSockets: full real-time, bidirectional communication.