Older web pages reloaded completely every time they needed new data. AJAX lets a page fetch data in the background and update only the part that changes.
Introduction and Purpose
AJAX stands for Asynchronous JavaScript And XML. It is not a language but a technique that uses JavaScript to send requests to a server in the background and update part of a page with the response, without reloading the whole page. Despite the name, the data is now usually JSON or plain text rather than XML. The term was coined in 2005, when applications such as Google Maps and Gmail made it famous.
Definition: AJAX. Asynchronous JavaScript and XML, a technique in which JavaScript exchanges data with a server in the background and updates part of a page without reloading it.
How AJAX Works
- An event occurs on the page, such as a click or typing in a search box. 2. JavaScript creates a request object, either XMLHttpRequest or the modern fetch() API. 3. The request is sent to the server asynchronously, so the page stays usable. 4. The server processes it and returns data. 5. JavaScript receives the response in a callback or a promise and updates the DOM. With XMLHttpRequest, the steps are: const xhr = new XMLHttpRequest(); xhr.open("GET", "data.txt"); xhr.onload = () => { ... xhr.responseText ... }; xhr.send();. The readyState goes from 0 to 4 (done), and status 200 means success. With fetch: fetch("data.txt").then(r => r.text()).then(t => ...), or with async and await.
Advantages
AJAX gives faster, smoother pages, since only data is transferred, not the whole page. Pages feel like desktop applications. It reduces server load and bandwidth, and lets users keep working while data loads. It enables features such as live search suggestions, infinite scroll, chat, auto-save and form checks such as "username already taken".
Disadvantages
Content loaded by AJAX may not be seen by search engines. The browser's back button and bookmarks may not work as expected without extra code. It depends on JavaScript, and it adds complexity and security concerns, such as cross-site scripting. Browsers block requests to other domains unless the server allows them (CORS), and pages cannot fetch local files when opened directly from disk, so a local server is needed.
AJAX-Based Applications and Alternatives
AJAX is used in Google Maps (loading map tiles as you move), Gmail, social media feeds, search suggestions and shopping carts. Alternatives and successors include the Fetch API, libraries such as Axios and jQuery's $.ajax, WebSockets for two-way real-time data, Server-Sent Events for server pushes, and frameworks such as React and Angular, which build on these.
Table 4.3: XMLHttpRequest and fetch
| Feature | XMLHttpRequest | fetch() |
|---|---|---|
| Style | Callbacks and events | Promises, async/await |
| Age | Since early 2000s | Modern (2015) |
| Response | responseText, responseXML | r.text(), r.json() |
| Code length | Longer | Shorter |
Example 4.3: Loading a text file with AJAX
Problem: On clicking a button, load the contents of notice.txt from the server and show it in a div without reloading the page.
Solution:
- Add a button and an empty div.
- In the click handler, call fetch("notice.txt").
- Convert the response with r.text() and put it in the div.
- Catch errors and show a message.
Result: The notice appears in the div; the rest of the page is untouched. (The page must be served by a web server.)
<button id="load">Show Notice</button>
<div id="notice">No notice loaded.</div>
<script>
const out = document.getElementById("notice");
document.getElementById("load").onclick = async () => {
try {
const r = await fetch("notice.txt"); // AJAX request
if (!r.ok) throw new Error("HTTP " + r.status);
out.textContent = await r.text();
} catch (err) {
out.textContent = "Could not load: " + err;
}
};
</script>
Common mistakes
- Opening the page directly from disk, where browsers block fetch requests.
- Using the response before it arrives, forgetting that AJAX is asynchronous.
- Ignoring errors such as status 404.
Key takeaways
- AJAX updates part of a page without a reload.
- It uses XMLHttpRequest or fetch, asynchronously.
- Advantages: speed and smoothness; disadvantages: SEO, back button, complexity.
- Alternatives: Fetch API, Axios, WebSockets, Server-Sent Events.
Practice questions
- What does AJAX stand for?
- What is the main advantage of AJAX?
- What does readyState 4 mean in XMLHttpRequest?
Answers to the practice questions
- Asynchronous JavaScript And XML.
- Parts of a page can be updated with data from the server without reloading the whole page.
- The request is complete.
Sources
- Official BCA syllabus Web Technologies, course code 25BCA402SEC02, Unit IV
