JavaScript AJAX
JavaScript AJAX (Asynchronous JavaScript and XML)
AJAX allows web pages to update content without reloading the entire page.
It communicates with a server in the background and fetches data asynchronously.
🎯 Why Use AJAX?
| Feature | Benefit |
|---|---|
| Asynchronous | Page does not reload |
| Faster | Only required data loads |
| Used in | APIs, search suggestions, forms, dynamic content |
Example: When searching in Google, results appear instantly — that’s AJAX.
📌 AJAX Uses in Real World
-
Auto-search suggestions
-
Loading data dynamically (products, users)
-
Submitting forms in the background
-
Fetching live data (weather, stock updates)
🚀 AJAX Methods in JavaScript
| Method | Description |
|---|---|
XMLHttpRequest |
Old traditional method |
fetch() |
Modern and simpler |
| Libraries | jQuery AJAX (optional) |
1️⃣ AJAX with XMLHttpRequest (Old Method)
2️⃣ AJAX with fetch() (Modern Way — Recommended)
📩 Sending Data (POST Request)
Using Fetch
🌐 AJAX Response Types
| Type | Example |
|---|---|
| Text | Plain text file |
| JSON | Most common API response |
| XML | Old format |
| HTML | Insert into webpage section |
🎛️ AJAX with DOM Example (Display Fetched Data)
🔒 AJAX Error Handling
💾 AJAX + JSON + LocalStorage Example
🧠 AJAX Keywords Summary
| Term | Meaning |
|---|---|
| Async | Runs without blocking UI |
| Request | Asking server for data |
| Response | Server sends data |
| API | Service providing data |
| JSON | Format used to send data |
⭐ Summary
| Feature | Old | New |
|---|---|---|
| Syntax | XMLHttpRequest |
fetch() |
| Easier? | ❌ Hard | ✅ Simple |
| Supports Promise? | ❌ | ✅ Yes |
