JavaScript AJAX
Learn how to use AJAX to communicate with servers asynchronously.
What is AJAX?
AJAX allows you to send/receive data asynchronously. Modern apps use it for:
- Loading content dynamically
- Sending form data
- Fetching data from APIs
XMLHttpRequest Example (GET)
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log("Data:", JSON.parse(xhr.responseText));
}
};
xhr.send();
XMLHttpRequest Example (POST)
let xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
console.log("Response:", xhr.responseText);
};
xhr.send(JSON.stringify({
title: "AJAX Post",
body: "This is a test",
userId: 1
}));
Modern Alternative: Fetch API
Fetch API is simpler and returns Promises:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
XMLHttpRequest vs Fetch
| Feature | XMLHttpRequest | Fetch API |
|---|---|---|
| Syntax | Verbose | Simpler |
| Promise-based | No | Yes |
| Modern Usage | Legacy support | Recommended |
Fetch API Example:
fetch("data.json")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
Practice Task
Use XMLHttpRequest to load a user's name from the API and display it in the console:
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/users/1", true);
xhr.onload = function () {
if (xhr.status === 200) {
let user = JSON.parse(xhr.responseText);
console.log("User Name:", user.name);
}
};
xhr.send();