AJAX Introduction in JavaScript
15 April 2025 | Category: JavaScript
What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
It’s a technique that allows webpages to send and receive data from a server without refreshing the page.
🔥 In simple words: AJAX = Load data without reloading the page!
âś… Why Use AJAX?
With AJAX, you can:
- Get data from a server without reloading the page
- Send data to a server behind the scenes
- Make fast, dynamic, user-friendly web apps (like Gmail, Twitter, Facebook feeds, etc.)
🔄 Traditional Page vs AJAX Page
Feature | Traditional Request | AJAX Request |
---|---|---|
Page Reload | Yes | ❌ No |
User Experience | Slower | Smooth, fast |
Server Communication | Full page reload | Only fetches data |
⚙️ How AJAX Works (Step-by-Step)
- JavaScript sends a request to the server using an AJAX method.
- Server processes the request and sends back a response (usually in JSON or XML).
- JavaScript receives the response and updates the webpage dynamically.
đź§° Ways to Use AJAX
JavaScript offers multiple ways to use AJAX:
Method | Description |
---|---|
XMLHttpRequest | Traditional AJAX method |
fetch() API | Modern, simpler AJAX method |
Axios | External library for AJAX |
jQuery AJAX | Older, library-based method |
🚀 Example Using fetch()
(Modern Way)
<button onclick="loadData()">Load User</button>
<p id="output"></p>
<script>
function loadData() {
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(data => {
document.getElementById("output").innerText = `Name: ${data.name}`;
})
.catch(error => console.error("Error:", error));
}
</script>
✔️ Output: Displays user name fetched from API without page reload.
đź§ Note on JSON vs XML
- Modern APIs use JSON (JavaScript Object Notation).
- XML is rarely used now for web APIs.
- AJAX still keeps the old name but mostly uses JSON today.
âś… Summary
Feature | Description |
---|---|
AJAX | Load/send data without refreshing the page |
Key Benefit | Smooth user experience |
Tools | fetch() , XMLHttpRequest , Axios |
Data Type | JSON (mostly), XML (rare) |