AJAX – Server Response
15 April 2025 | Category: JavaScript
What is a Server Response?
When you send a request to a server using AJAX, the server processes it and sends a response back to your JavaScript code.
The server response contains:
- ✅ A status code (e.g., 200 for success)
- 📦 Data (usually in JSON, XML, or plain text format)
You can then use JavaScript to display or process this data without reloading the webpage.
🔄 How to Handle a Server Response in AJAX?
When using XMLHttpRequest
, you handle the response using the onload
or onreadystatechange
event.
🚀 Example – Display Server Response Using AJAX
<button onclick="getData()">Get Data</button>
<p id="output"></p>
<script>
function getData() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onload = function () {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText); // Convert JSON string to object
document.getElementById("output").innerText = `Title: ${response.title}`;
} else {
document.getElementById("output").innerText = "Error loading data.";
}
};
xhr.send();
}
</script>
✅ Output: Displays the title from the JSON response without reloading the page.
📑 Important XHR Response Properties
Property | Description |
---|---|
xhr.responseText | Raw response as a string (JSON, text, etc.) |
xhr.responseXML | If response is XML, you can parse it using this |
xhr.status | HTTP status code (e.g., 200 OK, 404 Not Found) |
xhr.readyState | Tracks the state of the request (0 to 4) |
⚠️ Handling Errors
Always check for errors in your response:
xhr.onload = function () {
if (xhr.status === 200) {
console.log("Success:", xhr.responseText);
} else {
console.error("Error:", xhr.status);
}
};
✅ Common HTTP Status Codes
Code | Meaning |
---|---|
200 | OK (Success) ✅ |
201 | Created |
400 | Bad Request ❌ |
404 | Not Found ❌ |
500 | Server Error ❌ |
🧠 Note: Response Format Matters
- Most modern APIs return JSON.
- Always parse JSON using
JSON.parse()
if you’re usingresponseText
.
const jsonData = JSON.parse(xhr.responseText);
🔚 Summary
- AJAX lets you get server responses without reloading the page.
- Use
xhr.responseText
to access the data. - Always check
xhr.status
to handle errors properly. - Convert JSON responses using
JSON.parse()
.