In the early days of web development, every user interaction—such as submitting a form or clicking to the next page—required a full reload of the entire web page. This meant a slower user experience and unnecessary server load. With the advent of AJAX technology, the way web applications operate changed completely, enabling background data updates without reloading the page.
What is AJAX and How Does It Work?
AJAX stands for Asynchronous JavaScript and XML. Although it includes XML in its name, the lighter JSON format is almost exclusively used for data transfer today. The key word in the name is asynchronous, which means the mechanism operates in the background without interrupting the user's browsing or blocking the web interface.
| Step | Action | Description |
|---|---|---|
| 1. Event | User click or input | JavaScript detects an event (e.g., button click or text input). |
| 2. Request | Sending to server | The browser sends an HTTP request (GET or POST) to the server in the background. |
| 3. Processing | Server logic | PHP or another backend processes the data and returns a response (JSON). |
| 4. DOM Update | Display on page | JavaScript receives the data and updates only a specific HTML element. |
Advantages of Using AJAX Technology
Using asynchronous requests brings significant advantages to both developers and end users of web applications.
- Better User Experience (UX): The page responds quickly and smoothly, similar to a desktop application.
- Lower Bandwidth Usage: Only the necessary data is transferred, not the entire HTML structure.
- Reduced Server Load: The server processes only specific data requests instead of re-rendering the whole page.
Example of Using Fetch API in JavaScript
In the past, the XMLHttpRequest object was used for AJAX, but in modern JavaScript, we primarily use the much cleaner fetch() API.
// Function for fetching product details in the background
function getProductDetails(productId) {
fetch('/api/products.php?id=' + productId)
.then(response => {
if (!response.ok) {
throw new Error('Error fetching data');
}
return response.json();
})
.then(data => {
// Update only a specific element on the web page
document.getElementById('product-price').innerText = data.price + ' $';
document.getElementById('product-status').innerText = data.status;
})
.catch(error => {
console.error('AJAX error:', error);
});
}
Try Practical Examples in the Simulator
If you want to test AJAX requests in practice and explore various usage scenarios, check out the interactive examples in our AJAX Tutorial and Simulator.