An AJAX response is the data sent back from the server after an asynchronous request. The response can be in different formats like JSON, XML, HTML, or plain text, which JavaScript processes and updates the webpage dynamically without a reload.
Types of AJAX Responses
Response Type | Description |
JSON | JavaScript Object Notation (lightweight, most common) |
XML | Extensible Markup Language (older format) |
HTML | HTML content returned from the server |
Pain Text | Simple string responses |
Handling an AJAX Response with XMLHttpRequest
(Old Approach)
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) {
let response = xhr.responseText; // Get response as text
console.log("Raw Response:", response);
let jsonData = JSON.parse(response); // Convert to JSON
console.log("Parsed JSON:", jsonData);
document.getElementById("result").innerHTML = `<h3>${jsonData.title}</h3><p>${jsonData.body}</p>`;
}
};
xhr.send();
}
Key properties
xhr.responseText
→ Returns the response as plain text.JSON.parse(responseText)
→ Converts a JSON string to a JavaScript object.
Handling AJAX Response Using fetch()
(New Approach)
function fetchData() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json()) // Convert response to JSON
.then(data => {
console.log("Fetched Data:", data);
document.getElementById("result").innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`;
})
.catch(error => console.error("Error:", error));
}
Benefits of fetch()
- Returns a promise, making it easier to handle responses.
- Automatically supports JSON response with .json().
Handling AJAX Response with async/await
(Best Practice)
async function fetchDataAsync() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log("Async Data:", data);
document.getElementById("result").innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`;
} catch (error) {
console.error("Error:", error);
}
}
Why async/await
?
- Cleaner syntax (no
.then()
chaining). - Better error handling with
try...catch
.
Handling Different Response Types
Let's handle the different types of Ajax responses,
A. JSON Response
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json()) // Convert JSON response
.then(data => console.log(data));
- Common for APIs
- Easier to work with in JavaScript
B. XML Response
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/data.xml", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let xmlDoc = xhr.responseXML; // Parse XML response
console.log(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
}
};
xhr.send();
This approach is rarely used in modern APIs.
C. HTML Response
fetch("https://example.com/page.html")
.then(response => response.text()) // Convert response to text (HTML)
.then(data => document.getElementById("result").innerHTML = data);
This approach is useful for loading components dynamically.
D. Plain Text Response
fetch("https://example.com/message.txt")
.then(response => response.text())
.then(data => console.log("Text Response:", data));
This is simple for logs, messages, and status updates.
Handling AJAX Errors
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript AJAX Response</title>
</head>
<body>
<button id="fetchDate">Fetch Data</button>
<div id="output"></div>
<script>
document.getElementById("fetchDate").addEventListener("click", function(){
fetch("https://jsonplaceholder.typicode.com/invalid-url")
.then(response => {
if (!response.ok) throw new Error(`HTTP Error: ${response.status}`);
return response.json();
})
.then(data => {
document.getElementById("fetchDate").innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`
})
.catch(error => console.error("Fetch Error:", error));
});
</script>
</body>
</html>
The above code prints an error message on the console (Fetch Error: Error: HTTP Error: 404)
AJAX Response Lifecycle
sequenceDiagram
Browser->>Server: Sends AJAX Request
Server-->>Browser: Returns Response (JSON/XML/Text)
Browser->>JavaScript: Processes Response
JavaScript->>User: Updates UI Dynamically
I hope you understand the JavaScript Ajax response clearly.
Thanks!
Also, read: Explain the AJAX Request in javascript.
Leave Comment