AJAX Response
Handling server responses in AJAX
📨 What is an AJAX Response?
An AJAX response is data returned from the server after processing your request. You can receive responses as text, JSON, XML, or other formats and use them to update your webpage dynamically.
// Handle response
xhr.onload = function() {
console.log(xhr.responseText);
};
Response Properties
responseText
Response as plain text string
xhr.responseText
status
HTTP status code (200, 404, 500)
xhr.status
responseXML
Response as XML document
xhr.responseXML
statusText
Status message description
xhr.statusText
🔹 Handling Text Response
The responseText property contains server data as a plain text string. This is the most common way to receive and process server responses.
// Handle text response
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
// Get response as text
const response = xhr.responseText;
// Display in page
document.getElementById('output').innerHTML = response;
}
};
xhr.open('GET', 'message.txt', true);
xhr.send();
Output:
Welcome! This is the server response.
🔹 Handling JSON Response
JSON responses are widely used in modern web applications. They provide structured data that's easy to parse and work with in JavaScript.
// Handle JSON response
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
// Parse JSON response
const data = JSON.parse(xhr.responseText);
// Access data properties
console.log(data.name); // "John Doe"
console.log(data.email); // "[email protected]"
// Display data
document.getElementById('output').innerHTML =
'Name: ' + data.name + '<br>Email: ' + data.email;
}
};
xhr.open('GET', 'user.json', true);
xhr.send();
Output:
Name: John Doe
Email: [email protected]
🔹 HTTP Status Codes
Status codes indicate whether requests succeeded or failed. Understanding these codes helps you handle different scenarios appropriately and provide better user feedback.
Common Status Codes:
- 200 OK: Request successful
- 201 Created: Resource created successfully
- 400 Bad Request: Invalid request syntax
- 404 Not Found: Resource doesn't exist
- 500 Internal Server Error: Server error occurred
xhr.onload = function() {
if (xhr.status === 200) {
console.log('Success!');
} else if (xhr.status === 404) {
console.log('Not found!');
} else {
console.log('Error: ' + xhr.status);
}
};
🔹 Error Handling
Proper error handling ensures your application responds gracefully to network issues, server errors, or invalid responses.
const xhr = new XMLHttpRequest();
// Handle successful response
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('result').innerHTML = xhr.responseText;
} else {
document.getElementById('result').innerHTML =
'Error: ' + xhr.status + ' - ' + xhr.statusText;
}
};
// Handle network errors
xhr.onerror = function() {
document.getElementById('result').innerHTML =
'Network error occurred!';
};
// Handle timeout
xhr.ontimeout = function() {
document.getElementById('result').innerHTML =
'Request timed out!';
};
xhr.timeout = 5000; // 5 seconds
xhr.open('GET', 'data.php', true);
xhr.send();
🔹 Complete Response Example
Here's a comprehensive example showing how to handle different response types and error scenarios:
<!DOCTYPE html>
<html>
<body>
<h2>User Information</h2>
<button onclick="loadUser()">Load User Data</button>
<div id="userInfo"></div>
<script>
function loadUser() {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
// Parse JSON response
const user = JSON.parse(xhr.responseText);
// Display user data
document.getElementById('userInfo').innerHTML = `
<h3>${user.name}</h3>
<p>Email: ${user.email}</p>
<p>Age: ${user.age}</p>
`;
} else {
document.getElementById('userInfo').innerHTML =
'Error loading user data!';
}
};
xhr.onerror = function() {
document.getElementById('userInfo').innerHTML =
'Network error!';
};
xhr.open('GET', 'user.json', true);
xhr.send();
}
</script>
</body>
</html>