AJAX (Asynchronous JavaScript and XML) is a technique used in web development that allows a web page to communicate with a server without reloading the entire page. It makes web applications faster, smoother, and more dynamic.
š§ What Does AJAX Do?
Sends data to a server and receives a response asynchronously
Updates parts of a web page without refreshing the whole page
Works with data formats like JSON, XML, or plain text
š§± How AJAX Works (Simplified Steps)
JavaScript creates an
XMLHttpRequest
or usesfetch()
API.A request is sent to the server (e.g., to get or submit data).
The server processes the request and sends back data.
JavaScript receives the response and updates the DOM dynamically.
š§Ŗ Example Using fetch()
(Modern AJAX)
// Fetch data from an API and update the page
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
document.getElementById('result').innerHTML = data.name;
})
.catch(error => console.error('Error:', error));
š¹ļø Classic AJAX with XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
document.getElementById("result").innerHTML = data.name;
}
};
xhr.send();
ā Benefits of AJAX
Faster interactions and smoother user experience
Reduces server load and bandwidth usage
Only updates necessary parts of a page
ā ļø Limitations / Considerations
Requires JavaScript to be enabled in the browser
More complex debugging compared to traditional form submissions
Doesnāt change the browser history unless handled manually (e.g., via History API)
š Common Use Cases
Live search suggestions
Form submissions without page reloads
Real-time updates (e.g., chat apps, notifications)
Auto-refreshing data (stocks, weather, etc.)