Web Technology IIUnit 816 min read
AJAX, Asynchronous Programming & Real-Time Web Apps
Unit 8 of Web Technology II explores AJAX (Asynchronous JavaScript and XML), its core mechanism XMLHttpRequest, JSON data handling, and modern alternatives like Fetch API. It covers how to build dynamic, responsive web apps without full page reloads—key for modern platforms like eSewa, Daraz, and Ncell. Includes hands-
TAKEAWAYS:
- AJAX enables asynchronous data exchange between client and server using
XMLHttpRequestorfetch(), eliminating page reloads. - JSON is the preferred data format for AJAX due to its lightweight syntax and ease of parsing in JavaScript.
- The Fetch API (modern replacement for
XMLHttpRequest) simplifies HTTP requests with cleaner syntax and built-in Promise support. - Event-driven programming (e.g.,
onreadystatechange,then/catch) handles asynchronous responses dynamically. - Real-world applications include live updates (e.g., stock prices on NEPSE), form validation (e.g., Khalti payment checks), and chat apps (e.g., Pathao driver-passenger messaging).
- Security risks like CSRF and XSS must be mitigated in AJAX-based apps (e.g., using tokens or sanitizing inputs).
1. What is AJAX?
AJAX (Asynchronous JavaScript and XML) is a client-side scripting technique that allows web pages to fetch and send data to a server asynchronously (without reloading the entire page). It combines:
- JavaScript (for dynamic updates),
- XML/JSON (for data exchange),
- HTTP (for communication),
- DOM (to update page content dynamically).
Why AJAX?
Before AJAX, every interaction (e.g., submitting a form, clicking a button) required a full page reload. AJAX changed this by:
- Improving user experience (e.g., auto-complete search like Google, live chat like Pathao).
- Reducing server load (only data, not entire HTML, is transferred).
- Enabling real-time apps (e.g., stock tickers, collaborative editing).
2. Core Components of AJAX
sequenceDiagram
participant Client as Browser (JavaScript)
participant Server as Web API
Client->>Server: GET /users (XHR/Fetch)
Server-->>Client: {"status":"success", "data":[...]} (JSON)
Client->>Client: Update DOM
Note over Client,Server: No full page reloadAJAX request-response cycle (XHR/Fetch)A. XMLHttpRequest (XHR) Object
The traditional way to send HTTP requests from JavaScript. Key properties/methods:
classDiagram
class XMLHttpRequest {
+open(method, url, async, username, password)
+send(body)
+onreadystatechange() event
+readyState: 0-4
+status: 200, 404, etc.
+responseText: string
+responseXML: XML object
}How it works:
- Create an
XMLHttpRequestobject. - Open a connection (
GET,POST, etc.) to a server endpoint. - Send data (if needed, e.g., form inputs).
- Listen for the
onreadystatechangeevent (triggered whenreadyStatechanges). - Check
status(e.g.,200= success) and parseresponseText(usually JSON).
Example: Fetching User Data from a Server
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/users", true); // async = true
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const users = JSON.parse(xhr.responseText);
console.log(users); // [{id: 1, name: "Alice"}, ...]
}
};
xhr.send();
B. JSON (JavaScript Object Notation)
A lightweight data format for AJAX responses. Example:
{
"status": "success",
"data": {
"user": {
"id": 123,
"name": "John Doe",
"email": "john@example.com"
}
}
}
Why JSON?
- Easier to parse than XML in JavaScript (
JSON.parse()). - Smaller file size → faster loading.
- Used by APIs like eSewa’s payment status checks or Daraz’s product search.
3. Modern AJAX: Fetch API
The Fetch API (introduced in ES6) is a modern replacement for XMLHttpRequest. It uses Promises for cleaner asynchronous code.
Key Features:
- Returns a Promise (supports
.then()/.catch()). - Simpler syntax (no
readyStateoronreadystatechange). - Built-in support for HTTP headers and request options.
Example: Fetching Data with Fetch API
fetch("https://api.example.com/users")
.then(response => {
if (!response.ok) throw new Error("Network error");
return response.json(); // Parse JSON
})
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
Comparison: XMLHttpRequest vs. Fetch API
| Feature | XMLHttpRequest | Fetch API |
|---|---|---|
| Syntax | Verbose (callbacks) | Clean (Promises) |
| Error Handling | Manual (status checks) |
Built-in (response.ok) |
| Headers | Manual (setRequestHeader) |
Easy ({ headers: {...} }) |
| Progress Tracking | Yes (onprogress) |
No (use ReadableStream for advanced cases) |
| Browser Support | Older browsers | Modern browsers (IE11+ with polyfill) |
4. Real-World Applications of AJAX
A. eSewa: Real-Time Payment Status
- Problem: Users expect instant updates after paying bills (e.g., electricity, internet).
- Solution: eSewa’s backend sends AJAX requests to check payment status every 2 seconds without refreshing the page.
- How it works:
- User submits payment → frontend sends
POSTto eSewa’s server. - Server processes payment and returns a JSON response with status.
- Frontend updates the UI dynamically using
fetch()in a loop:function checkPaymentStatus() { fetch("/api/payment/status?orderId=123") .then(res => res.json()) .then(data => { if (data.status === "completed") { document.getElementById("status").textContent = "Paid!"; clearInterval(interval); } }); } const interval = setInterval(checkPaymentStatus, 2000);
- User submits payment → frontend sends
B. Daraz: Live Product Search
- Problem: Users typing in search boxes expect instant suggestions (e.g., "shirt" → "white shirt", "cotton shirt").
- Solution: Daraz’s search bar uses AJAX to fetch suggestions as the user types.
- How it works:
- User types "s" →
keyupevent triggers afetch()call. - Server returns JSON with matching products:
["shirt", "shoes", "socks", "sandal"] - Frontend updates a dropdown menu dynamically.
- User types "s" →
C. Pathao: Driver-Passenger Chat
- Problem: Riders and drivers need real-time messaging without page reloads.
- Solution: Pathao uses WebSockets (an advanced AJAX alternative) for bidirectional communication, but the initial connection and message handling rely on AJAX-like principles.
- How it works:
- Passenger sends a message → frontend sends
POSTto Pathao’s server. - Server broadcasts the message to the driver’s device via WebSocket.
- Driver’s app receives the message and updates the chat UI instantly.
- Passenger sends a message → frontend sends
5. AJAX Workflow: Step-by-Step Example
Let’s build a live traffic route updater (like NTC’s real-time bus tracking).
Scenario:
A user selects a bus route (e.g., "Kathmandu to Bhaktapur"), and the app fetches live location updates every 5 seconds.
Steps:
HTML: A button to fetch updates and a
<div>to display locations.<button id="start">Track Bus</button> <div id="location"></div>JavaScript: Use
fetch()to poll the server.let intervalId; document.getElementById("start").addEventListener("click", () => { intervalId = setInterval(fetchLocation, 5000); }); function fetchLocation() { fetch("https://api.ntc.gov.np/bus/location?route=KTM-BKT") .then(res => res.json()) .then(data => { document.getElementById("location").innerHTML = `<p>Bus at: ${data.latitude}, ${data.longitude}</p>`; }) .catch(err => console.error("Error:", err)); }Server Response (JSON):
{ "latitude": 27.7172, "longitude": 85.3240, "status": "moving" }
Visual: AJAX Request-Response Cycle
sequenceDiagram
participant User
participant Browser
participant Server
User->>Browser: Clicks "Track Bus" button
Browser->>Server: fetch("/api/bus/location", { route: "KTM-BKT" })
Server-->>Browser: JSON: { latitude: 27.7172, ... }
Browser->>User: Updates UI dynamically
Note right of Browser: Repeat every 5 seconds6. Handling Errors in AJAX
AJAX requests can fail due to:
- Network issues (no internet).
- Server errors (500, 404).
- Invalid data (malformed JSON).
Best Practices:
- Check
response.ok(Fetch API) orstatus(XHR). - Use
.catch()(Fetch) ortry-catch(XHR). - Show user-friendly messages (e.g., "Failed to load data. Retry?").
Example: Error Handling with Fetch
fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) throw new Error("Server error");
return response.json();
})
.then(data => console.log(data))
.catch(error => {
console.error("Fetch failed:", error);
alert("Could not load data. Check your connection.");
});
7. Security Considerations
AJAX introduces new security risks:
| Risk | Mitigation Strategy |
|---|---|
| CSRF (Cross-Site Request Forgery) | Use CSRF tokens in requests. |
| XSS (Cross-Site Scripting) | Sanitize dynamic content (textContent vs. innerHTML). |
| Data Leakage | Avoid logging sensitive data (e.g., passwords). |
| Man-in-the-Middle Attacks | Use HTTPS (not HTTP). |
Example: CSRF Protection in AJAX
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch("/api/transfer", {
method: "POST",
headers: { "X-CSRF-Token": token },
body: JSON.stringify({ amount: 1000 })
});
8. AJAX Alternatives
While AJAX is powerful, modern web apps often use:
- Fetch API (simpler than XHR).
- WebSockets (for real-time bidirectional communication, e.g., WhatsApp).
- Server-Sent Events (SSE) (server pushes updates to client, e.g., live sports scores).
- GraphQL (efficient data fetching, used by GitHub, Shopify).
Comparison Table:
| Technique | Use Case | Pros | Cons |
|---|---|---|---|
| AJAX (XHR/Fetch) | One-time or periodic requests | Works in all browsers | Not real-time |
| WebSockets | Chat, live updates (e.g., Pathao) | Real-time, bidirectional | Complex setup |
| SSE | Server-to-client updates | Simple, built into browsers | One-way only |
| GraphQL | Complex queries (e.g., APIs) | Flexible data fetching | Steeper learning curve |
9. Hands-On: Build a Simple AJAX App
Task: Create a to-do list app where users can add tasks via AJAX.
Steps:
HTML:
<input type="text" id="taskInput" placeholder="Add task"> <button id="addTask">Add</button> <ul id="taskList"></ul>JavaScript:
document.getElementById("addTask").addEventListener("click", () => { const task = document.getElementById("taskInput").value; fetch("/api/tasks", { method: "POST", body: JSON.stringify({ task }) }) .then(res => res.json()) .then(data => { document.getElementById("taskList").innerHTML += `<li>${data.task} <button onclick="deleteTask(${data.id})">Delete</button></li>`; }); }); function deleteTask(id) { fetch(`/api/tasks/${id}`, { method: "DELETE" }) .then(() => location.reload()); }Server-Side (PHP Example):
// Save task (POST /api/tasks) $data = json_decode(file_get_contents("php://input"), true); $task = $data['task']; $id = saveToDatabase($task); // Assume this function exists echo json_encode(["id" => $id, "task" => $task]); // Delete task (DELETE /api/tasks/:id) $id = $_GET['id']; deleteFromDatabase($id);
10. Exam Tip: How to Score Full Marks
- Define AJAX clearly (asynchronous + XML/JSON + dynamic updates).
- Show code snippets for both
XMLHttpRequestandfetch(). - Explain the
readyStateandstatusin XHR (common exam question). - Compare AJAX with traditional form submissions (table format works well).
- Include a real-world example (e.g., eSewa, Daraz) with code traces.
- Mention security risks (CSRF, XSS) and mitigations.
- For short-answer questions, use bullet points:
- AJAX = Asynchronous JavaScript and XML.
- Key object:
XMLHttpRequest(orfetch()). - Uses HTTP requests without page reload.
- Data format: JSON (preferred) or XML.
Past Exam Question Answer (Full Marks):
Q: What is XMLHttpRequest Object? Write AJAX script to demonstrate its use.
A:
The XMLHttpRequest object is a JavaScript API used to send asynchronous HTTP requests to a server. It allows fetching or sending data without reloading the page.
Script Example:
// Create XHR object
const xhr = new XMLHttpRequest();
// Configure request
xhr.open("GET", "https://api.example.com/data", true); // true = async
// Handle response
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
// Send request
xhr.send();
In the Real World
eSewa
- AJAX Use: When you pay a bill, eSewa’s frontend uses
fetch()to poll the server every few seconds for payment status updates (success/failure) without refreshing the page. - Why It Matters: Users see real-time confirmation (e.g., "Payment of Rs. 500 successful") instantly, reducing calls to customer support.
- AJAX Use: When you pay a bill, eSewa’s frontend uses
Khalti
- AJAX Use: During checkout, Khalti’s payment form validates card details in real-time using AJAX. As you type, the system checks if the card number is valid or if the CVV matches.
- How It Works:
document.getElementById("cardNumber").addEventListener("input", (e) => { fetch(`/api/validate-card?number=${e.target.value}`) .then(res => res.json()) .then(data => { if (data.valid) { document.getElementById("cardError").textContent = ""; } else { document.getElementById("cardError").textContent = "Invalid card"; } }); });
NEPSE (Nepal Stock Exchange)
- AJAX Use: The live stock price ticker on NEPSE’s website updates every second using AJAX. Instead of refreshing the page, the frontend fetches new prices via:
setInterval(() => { fetch("/api/stock/price?symbol=NEPSE") .then(res => res.json()) .then(data => { document.getElementById("price").textContent = data.price; }); }, 1000); - Why It Matters: Traders see real-time price changes without lag, critical for making split-second decisions.
- AJAX Use: The live stock price ticker on NEPSE’s website updates every second using AJAX. Instead of refreshing the page, the frontend fetches new prices via:
Pathao (Ride-Hailing App)
- AJAX Use: When you request a ride, Pathao’s app continuously checks driver availability in the background using AJAX. If no drivers are nearby, it shows "Finding a driver..." and updates dynamically.
- Code Snippet (Simplified):
function checkDriverAvailability() { fetch("/api/drivers/nearby?lat=27.7172&lng=85.3240") .then(res => res.json()) .then(data => { if (data.available) { document.getElementById("status").textContent = `Driver found: ${data.driverName} (${data.distance}m away)`; } else { document.getElementById("status").textContent = "No drivers nearby. Expanding search..."; } }); } setInterval(checkDriverAvailability, 3000); // Check every 3 seconds
Key Takeaways for Exams
- AJAX = Asynchronous + JavaScript + XML/JSON → Dynamic updates without page reload.
- Two main methods:
XMLHttpRequest(old) andfetch()(modern). - Real-world tie-ins: eSewa (payment status), Daraz (search), NEPSE (stock prices).
- Security: Always use HTTPS, CSRF tokens, and input sanitization.
- Error handling: Check
response.ok(Fetch) orstatus(XHR) and use.catch().
Based on the TU BIT syllabus for Web Technology II (BIT301), unit 8.
Discussion
Loading…