AJAX
What is AJAX?
"Update page without refresh"
AJAX (Asynchronous JavaScript and XML) is a technique for:
- Making asynchronous HTTP requests
- Updating page content without reload
- Better user experience
- Now primarily uses JSON, not XML
Background:
Before AJAX was invented, updating parts of a web page with new data meant reloading the entire page. Every time a user performed an action requiring fresh data from the server (like submitting a form, navigating, or refreshing content), the browser would reload the whole page, interrupting the user experience and losing any unsaved state.What changed with AJAX:
AJAX (Asynchronous JavaScript and XML) revolutionized this by enabling web pages to fetch data from the server asynchronously—without refreshing the page. This allows dynamic updates (like displaying new messages or live search results), smoother user interactions, and more responsive web applications.
How AJAX Works
XMLHttpRequest or Fetch API
Traditional (XMLHttpRequest):
const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/data");
xhr.onload = () => {
console.log(xhr.response);
};
xhr.send();
Modern (Fetch API):
fetch("/api/data")
.then((response) => response.json())
.then((data) => console.log(data));
"AJAX uses XMLHttpRequest or the modern Fetch API to make asynchronous HTTP requests."
Fetch API
Modern promise-based API
fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
"The Fetch API is the modern, promise-based approach to making HTTP requests in JavaScript."
Async/Await
Synchronous-looking async code
async function fetchData() {
try {
const response = await fetch("/api/data");
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
"Async/await provides a cleaner syntax for handling asynchronous operations with Fetch."
Benefits of AJAX
- Better UX: No page reloads
- Faster: Only update needed parts
- Interactive: Real-time updates
- Efficient: Less bandwidth
Common Use Cases
- Form submissions without reload
- Infinite scroll
- Search autocomplete
- Real-time updates
- Loading data dynamically
Error Handling
Check response.ok
fetch("/api/data")
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.catch((error) => console.error(error));
"Always check response.ok and handle errors appropriately in AJAX requests."
CORS and AJAX
Cross-origin requests need CORS
- Same-origin: Works directly
- Cross-origin: Requires CORS headers
- Preflight requests for complex calls
"AJAX requests to different origins require proper CORS configuration on the server."
"AJAX enables asynchronous HTTP requests without page reloads, improving user experience. Modern JavaScript uses the Fetch API with promises or async/await for cleaner code. AJAX is used for dynamic content updates, form submissions, and real-time features. Cross-origin requests require CORS configuration."
🧠 Ultra-Short Cheat Sheet
Asynchronous requests
No page reload
Fetch API (modern)
XMLHttpRequest (legacy)
Async/await syntax
Error handling
CORS for cross-origin