AJAX (Asynchronous JavaScript and XML) – Introduction
AJAX is a web development technique that allows web pages to communicate with a server asynchronously without reloading the entire page. This makes web applications faster, smoother, and more interactive.
Despite the name, AJAX is not limited to XML; it often uses JSON, plain text, or HTML as the data format.
Key Concepts
- Asynchronous: AJAX requests run in the background, so the user can continue interacting with the page.
- Partial Page Updates: Only the part of the page that needs new data is updated, instead of reloading the whole page.
- Client-Server Communication: AJAX allows sending and receiving data from the server using JavaScript.
- Data Formats: Common formats include JSON, XML, HTML, or plain text.
How AJAX Works
- The browser creates an XMLHttpRequest (XHR) object.
- The request is sent to the server.
- The server processes the request and sends a response.
- The client receives the response and updates the web page dynamically.
AJAX Using XMLHttpRequest (Old Way)
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("Response:", xhr.responseText);
}
};
xhr.send();
open()
→ Sets up the request (method, URL, async flag)onreadystatechange
→ Event triggered when request state changesreadyState === 4
→ Request completedstatus === 200
→ Request successfulsend()
→ Sends the request to the server
AJAX Using Fetch API (Modern Way)
The Fetch API is simpler and Promise-based.
fetch("<https://api.example.com/data>")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
Advantages over XMLHttpRequest:
- Cleaner syntax with Promises
- Easier error handling
- Works seamlessly with modern async/await
Example: Load Data Without Refresh
<button id="loadBtn">Load Data</button>
<div id="result"></div>
<script>
document.getElementById("loadBtn").addEventListener("click", () => {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
document.getElementById("result").innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`;
});
});
</script>