π AJAX Tutorial β Learn How to Make Web Pages Dynamic
π What is AJAX?
AJAX (Asynchronous JavaScript and XML) enables web pages to communicate with servers behind the scenesβwithout refreshing. Nowadays, it handles JSON, HTML, plain text, and more.
πͺ Why Use AJAX?
- β Create smoother user experiences
- π Update parts of a page dynamically
- β‘ Reduce server load and bandwidth
- β Load data incrementally (infinite scroll, live search)
βοΈ Setting Up Your Workspace
- Create an
index.html
andscript.js
file - Use any text editor (VS Code, Sublime)
- Optionally spin up a local server (
http-server
, PythonSimpleHTTPServer
) to test requests
π‘ Basic AJAX with Vanilla JavaScript
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Key points:
open(method, url, async)
onreadystatechange
andreadyState
status code checks
π AJAX with Fetch API
Modern, promise-based:
fetch('https://api.example.com/data')
.then(res => {
if (!res.ok) throw new Error('Network error');
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));
Or with async/await:
async function getData() {
try {
const res = await fetch('/api/data');
if (!res.ok) throw new Error('Fetch failed');
const data = await res.json();
console.log(data);
} catch (e) {
console.error(e);
}
}
π Handling JSON Data
Requests return JSON:
fetch('/api/users')
.then(res => res.json())
.then(users => {
users.forEach(u => {
document.body.insertAdjacentHTML('beforeend', `<p>${u.name}</p>`);
});
});
Use JSON.stringify()
to send JSON:
fetch('/api/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' })
});
π§© AJAX in jQuery
$.ajax({
url: '/api/data',
method: 'GET',
dataType: 'json',
success(data) { console.log(data); },
error(err) { console.error(err); }
});
Shorter:
$.getJSON('/api/data', data => console.log(data));
π Error Handling & Timeout
xhr.timeout = 5000;
xhr.ontimeout = () => console.error('Time out');
xhr.onerror = () => console.error('Request error');
Fetch example:
fetch('/api')
.then(res => res.ok ? res.json() : Promise.reject(res))
.catch(err => console.error('Error:', err));
π¦ AJAX Request Types
- GET: Fetch data
- POST: Send new data
- PUT/PATCH: Update resources
- DELETE: Remove resources
Setheaders
andbody
accordingly.
π RealβWorld AJAX Use Cases
- π Live search auto-suggestions
- π Form submissions without reload
- π Charts and dashboards updated in real-time
- π§΅ Infinite scroll on social feeds
π οΈ Best Practices
- π§ͺ Use async/await for clarity
- β
Always check
res.ok
- π Handle timeouts and errors gracefully
- π Avoid callback hell
- π Secure against XSS, CSRF, CORS issues
π Conclusion
AJAX is the magic behind modern web apps β live updates, seamless UX, and smarter data handling. From your first XMLHttpRequest to full-fledged fetch-based patterns, mastering AJAX makes you a frontend wizard. Keep practicing by building chats, maps, and dashboards with live data!
β FAQs
Q1: Is AJAX still relevant?
π
°οΈ Absolutely. It powers modern SPAs, real-time features, and micro-interactions.
Q2: Should I use fetch
or XMLHttpRequest
?
π
°οΈ Use fetch. Itβs cleaner, promise-based, and easier to read with async/await.
Q3: How to send POST data with AJAX?
π
°οΈ Include method: 'POST'
, headers: {'Content-Type': 'application/json'}
, and body: JSON.stringify(data)
in fetch or XHR.
Q4: Can AJAX call APIs from other domains?
π
°οΈ Yes, if CORS is configured properly on the server.
Q5: How do I test AJAX locally?
π
°οΈ Use a local dev server like httpβserver
or python -m http.server
, because AJAX wonβt work with plain file://
URLs.
Share Now :