AJAX (Asynchronous JavaScript and XML) is a technology that allows web pages to be updated dynamically without reloading the entire page. It enables data exchange in real time between the web browser and the server.
AJAX is not a programming language, but a combination of technologies,
- JavaScript (for making requests)
- XMLHttpRequest (XHR) / Fetch API (for handling data transfer)
- HTML and CSS (for UI updates)
- JSON / XML (for data exchange)
How AJAX Works?
- A user performs an action (for example, clicking a button).
- JavaScript sends an HTTP request to the server asynchronously.
- The server processes the request and sends back data (JSON, XML, or plain text).
- JavaScript updates the webpage without refreshing it.
Flow diagram of Working of AJAX
sequenceDiagram
User->>Browser: Clicks Button
Browser->>Server: Sends AJAX Request
Server->>Browser: Sends Response (JSON/XML)
Browser->>User: Updates Web Page Without Reloading
Basic Example: Fetching Data Using AJAX
Using XMLHttpRequest
(Old Way)
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript AJAX Example</title>
</head>
<body>
<button onclick="loadData()">Get Data</button>
<div id="result"></div>
<script>
function loadData() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
</body>
</html>
Explanation
- Creates an
XMLHttpRequest
object. - Sends a
GET
request to the server. - Updates the webpage without refreshing when data is received.
Modern Way: Using fetch()
API
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript AJAX Example</title>
</head>
<body>
<button onclick="fetchData()">Fetch Data</button>
<div id="output"></div>
<script>
function fetchData() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json()) // Convert response to JSON
.then(data => {
document.getElementById("output").innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`;
})
.catch(error => console.error("Error:", error));
}
</script>
</body>
</html>
Advantages of fetch()
:
- Simpler than
XMLHttpRequest
- Supports Promises for clean asynchronous code
- More powerful and flexible
Common HTTP Methods in AJAX
Method | Description |
GET |
Fetch data from the server (Read) |
POST |
Send data to the server (Create) |
PUT |
Update existing data (Modify) |
DELETE |
Remove data from the server |
I hope you understand clearly about the JavaScript AJAX.
Thanks!
Also Read: Handling JavaScript Asynchronous Operations with Promises and Async/Await
Leave Comment