Handling AJAX Responses is an important AJAX topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Handling AJAX Responses solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Handling AJAX Responses should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Handling AJAX Responses should be studied as a practical AJAX lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the ajax > handling-responses page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
When an XHR request completes, several properties on the object give you access to the response data:
// ---- Parsing JSON with responseType ----
const xhrJson = new XMLHttpRequest();
xhrJson.open('GET', '/api/users', true);
xhrJson.responseType = 'json'; // browser parses JSON automatically
xhrJson.onload = function () {
// xhr.response is already a JS object - no JSON.parse() needed
console.log(xhrJson.response[0].name);
};
xhrJson.send();
// ---- Parsing JSON manually from responseText ----
const xhrText = new XMLHttpRequest();
xhrText.open('GET', '/api/users', true);
xhrText.onload = function () {
try {
const users = JSON.parse(xhrText.responseText);
console.log(users);
} catch (e) {
console.error('Invalid JSON:', e.message);
}
};
xhrText.send();
// ---- Parsing XML ----
const xhrXml = new XMLHttpRequest();
xhrXml.open('GET', '/api/data.xml', true);
xhrXml.onload = function () {
const xmlDoc = xhrXml.responseXML;
const items = xmlDoc.getElementsByTagName('item');
Array.from(items).forEach(item => {
console.log(item.textContent);
});
};
xhrXml.send();
Always check the HTTP status code before processing the response. A completed XHR request (readyState 4) does not mean the request was successful.
| Code | Meaning | Action |
|---|---|---|
| 200 | OK | Process the response normally. |
| 201 | Created | Resource was created successfully. |
| 204 | No Content | Success but no body (common for DELETE). |
| 400 | Bad Request | Client sent invalid data. |
| 401 | Unauthorized | Authentication required. |
| 403 | Forbidden | Authenticated but not allowed. |
| 404 | Not Found | Resource does not exist. |
| 500 | Internal Server Error | Server-side bug. |
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/resource/42', true);
xhr.responseType = 'json';
xhr.onload = function () {
switch (true) {
case xhr.status >= 200 && xhr.status < 300:
console.log('Success:', xhr.response);
break;
case xhr.status === 400:
console.error('Bad request - check your input data');
break;
case xhr.status === 401:
console.warn('Not authenticated - redirect to login');
window.location.href = '/login';
break;
case xhr.status === 403:
console.error('Access denied');
break;
case xhr.status === 404:
console.error('Resource not found');
break;
case xhr.status >= 500:
console.error('Server error - try again later');
break;
default:
console.warn('Unexpected status:', xhr.status);
}
};
xhr.onerror = () => console.error('Network failure');
xhr.send();
// ---- Download an image as a Blob ----
const xhrBlob = new XMLHttpRequest();
xhrBlob.open('GET', '/images/photo.jpg', true);
xhrBlob.responseType = 'blob';
xhrBlob.onload = function () {
const blob = xhrBlob.response;
const url = URL.createObjectURL(blob);
document.getElementById('preview').src = url;
};
xhrBlob.send();
// ---- Download binary data as ArrayBuffer ----
const xhrBuf = new XMLHttpRequest();
xhrBuf.open('GET', '/data/binary.bin', true);
xhrBuf.responseType = 'arraybuffer';
xhrBuf.onload = function () {
const buffer = xhrBuf.response;
const view = new Uint8Array(buffer);
console.log('First byte:', view[0]);
};
xhrBuf.send();
When studying Handling AJAX Responses, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In AJAX, Handling AJAX Responses becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
const state = { topic: "Handling AJAX Responses", ready: true };
if (state.ready) {
console.log(state.topic + ": render or run the normal path");
}
const response = null;
const message = response?.message ?? "Handling AJAX Responses: show a clear fallback";
console.log(message);
Memorizing Handling AJAX Responses without the situation where it is useful.
Connect Handling AJAX Responses to a concrete AJAX task.
Testing Handling AJAX Responses only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Handling AJAX Responses.
Memorizing Handling AJAX Responses without the situation where it is useful.
Connect Handling AJAX Responses to a concrete AJAX task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in AJAX, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.