XMLHttpRequest Integration
By the end of this lesson you will be able to build a file upload with a real progress bar and a Cancel button, read and fix older XHR code with confidence, and convert an XHR function to fetch() without changing how it behaves.
What you should know first: Fetch API Integration, File Upload Controls and Multiple & Accept File Attributes. The JavaScript course lesson XMLHttpRequest & AJAX (Legacy) explains the history of AJAX, a basic GET and POST, the five readyState values and callback nesting. This lesson does not repeat them; it goes where XHR is still the right tool.
Why XMLHttpRequest still matters
XMLHttpRequest (XHR) is the object browsers used for background requests before fetch(). New code should use fetch(), but XHR is not gone:
- Upload progress. XHR has an
uploadobject that firesprogressevents while the request body is being sent.fetch()has no upload progress event, so file uploaders still use XHR. - Legacy code. Government portals, college ERPs, WordPress plugins and jQuery sites built over the last twenty years are full of XHR. You will maintain them.
- Interviews. "What does
readyState4 mean?" is still a common question.
Think of XHR as the old reliable Ambassador taxi. Newer cars are nicer for daily use, but it still does one job very well, and many garages still have it.
The XHR life cycle in one table
You create the object, open() it, attach listeners, then send() it. Listeners must be attached before send().
| Member | What it does |
|---|---|
open(method, url) | Sets the method and URL; asynchronous by default |
setRequestHeader(name, value) | Adds a header (after open(), before send()) |
responseType | ""/"text", "json", "blob", "arraybuffer" or "document" |
timeout | Milliseconds before giving up; fires timeout |
send(body) | Starts the request; body may be a string, FormData, Blob or URLSearchParams |
abort() | Cancels; fires abort |
readyState | 0 to 4; 4 (DONE) means finished, successfully or not |
status | HTTP status, or 0 when there was no HTTP answer (network error, CORS, abort) |
response | The body, already converted according to responseType |
Events fire on the XHR object for the download side and on xhr.upload for the upload side:
| Event | Meaning |
|---|---|
loadstart | The transfer started |
progress | More bytes moved; read loaded, total and lengthComputable |
load | Finished with an HTTP response (any status, even 404) |
error | Failed without an HTTP response |
abort | Cancelled with abort() |
timeout | The timeout time ran out |
loadend | Always fires last, after any of the four above |
With responseType = "json", the browser parses the body for you. If the body is not valid JSON, response is simply null; no error is thrown. Always check status before trusting response.
Live coding: an upload with a real progress bar
Farhan is building a "Upload your marksheet" page for a college in Jaipur. Students on slow mobile data need to see how much is left, and they need a Cancel button.
Step 1: an <input type="file">, a <progress> element and two buttons. A second button creates a 3 MB test file in memory, so you can try it without choosing a file.
Step 2: put the file into FormData, the same format a normal <form enctype="multipart/form-data"> sends.
Step 3: listen to xhr.upload for progress and update the bar. Listen to the XHR itself for the server's answer.
Step 4: Cancel calls xhr.abort(), and loadend re-enables the buttons whatever happened.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload marksheet</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
progress { width: 100%; max-width: 28rem; height: 1.2rem; }
#log { background: #f5f5f5; padding: 8px; max-height: 12rem; overflow: auto; }
</style>
</head>
<body>
<h1>Upload your marksheet</h1>
<p>
<label for="file">Marksheet (PDF or image)</label>
<input type="file" id="file" accept=".pdf,image/*">
</p>
<p>
<button type="button" id="upload">Upload chosen file</button>
<button type="button" id="test">Upload a 3 MB test file</button>
<button type="button" id="cancel" disabled>Cancel</button>
</p>
<progress id="bar" max="100" value="0" aria-label="Upload progress"></progress>
<p id="status" role="status">No upload yet.</p>
<pre id="log"></pre>
<script>
const bar = document.querySelector("#bar");
const status = document.querySelector("#status");
const log = (text) => (document.querySelector("#log").textContent += text + "\n");
let xhr = null;
function upload(file) {
const data = new FormData();
data.append("student", "Farhan Khan");
data.append("marksheet", file, file.name);
xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");
xhr.responseType = "json";
xhr.timeout = 60000;
xhr.upload.addEventListener("loadstart", () => log("upload: loadstart"));
xhr.upload.addEventListener("progress", (event) => {
if (!event.lengthComputable) return;
const percent = Math.round((event.loaded / event.total) * 100);
bar.value = percent;
status.textContent = `Uploading: ${percent}% (${(event.loaded / 1048576).toFixed(1)} of ${(event.total / 1048576).toFixed(1)} MB)`;
});
xhr.upload.addEventListener("load", () => log("upload: all bytes sent"));
xhr.addEventListener("load", () => {
log(`load: status ${xhr.status}`);
if (xhr.status >= 200 && xhr.status < 300) {
status.textContent = `Uploaded. Server reference number: ${xhr.response?.id}.`;
} else {
status.textContent = `The server refused the file (status ${xhr.status}).`;
}
});
xhr.addEventListener("error", () => { log("error"); status.textContent = "Network error. Please try again."; });
xhr.addEventListener("timeout", () => { log("timeout"); status.textContent = "The upload took too long."; });
xhr.addEventListener("abort", () => { log("abort"); status.textContent = "Upload cancelled."; bar.value = 0; });
xhr.addEventListener("loadend", () => {
log("loadend");
document.querySelector("#cancel").disabled = true;
document.querySelector("#upload").disabled = false;
document.querySelector("#test").disabled = false;
});
document.querySelector("#cancel").disabled = false;
document.querySelector("#upload").disabled = true;
document.querySelector("#test").disabled = true;
bar.value = 0;
status.textContent = "Starting upload...";
log(`sending ${file.name} (${(file.size / 1048576).toFixed(1)} MB)`);
xhr.send(data);
}
document.querySelector("#upload").addEventListener("click", () => {
const file = document.querySelector("#file").files[0];
if (file) upload(file);
else status.textContent = "Choose a file first, or use the test file.";
});
document.querySelector("#test").addEventListener("click", () => {
const bytes = new Uint8Array(3 * 1024 * 1024); // 3 MB of zeros
upload(new File([bytes], "test-marksheet.pdf", { type: "application/pdf" }));
});
document.querySelector("#cancel").addEventListener("click", () => xhr?.abort());
</script>
</body>
</html>Press "Upload a 3 MB test file". The bar fills, the status shows the percentage and megabytes, and the log reads sending test-marksheet.pdf (3.0 MB), upload: loadstart, upload: all bytes sent, load: status 201 and loadend. The status ends with "Server reference number: 101." On a fast connection the bar may jump almost straight to 100%. In DevTools, choose "Slow 4G" or "3G" in the Network panel's throttling menu to watch it move, and press Cancel halfway: the log shows abort and then loadend.
The test server does not store the file; it just answers 201 Created. A real PHP endpoint would read it from $_FILES['marksheet'], check its type and size again on the server, and save it outside the web root.
Converting XHR code to fetch
When you maintain old code, convert XHR helpers to fetch() one at a time, and keep the behaviour the same. Here is a typical helper from an older project, with its modern replacement:
// Before: XHR with callbacks
function getStudent(id, onSuccess, onError) {
const xhr = new XMLHttpRequest();
xhr.open("GET", `/api/students/${id}`);
xhr.responseType = "json";
xhr.timeout = 8000;
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) onSuccess(xhr.response);
else onError(new Error(`HTTP ${xhr.status}`));
};
xhr.onerror = () => onError(new Error("Network error"));
xhr.ontimeout = () => onError(new Error("Timed out"));
xhr.send();
}
// After: fetch with async/await, same rules
async function getStudent(id) {
const response = await fetch(`/api/students/${id}`, { signal: AbortSignal.timeout(8000) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}| XHR | fetch |
|---|---|
xhr.onload + check status | await fetch() + check response.ok |
xhr.onerror | The promise rejects with TypeError |
xhr.timeout = 8000 + ontimeout | signal: AbortSignal.timeout(8000), TimeoutError |
xhr.abort() | controller.abort(), AbortError |
responseType = "json" | await response.json() (throws on bad JSON instead of giving null) |
withCredentials = true | credentials: "include" |
xhr.upload.onprogress | No equivalent: keep XHR for upload progress |
Callers change too: getStudent(7, show, fail) becomes getStudent(7).then(show, fail), or try { show(await getStudent(7)); } catch (e) { fail(e); }. Change the callers in the same commit, and test the error paths, not just success.
Step 5: the same request both ways
This example runs the old and the new version of one helper side by side, against a post that exists and one that does not.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>XHR vs fetch</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
table { border-collapse: collapse; }
th, td { border: 1px solid #ccc; padding: 6px 10px; text-align: left; }
</style>
</head>
<body>
<table>
<thead><tr><th>Request</th><th>XHR result</th><th>fetch result</th></tr></thead>
<tbody id="rows"></tbody>
</table>
<script type="module">
const API = "https://jsonplaceholder.typicode.com";
function getPostXhr(id) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", `${API}/posts/${id}`);
xhr.responseType = "json";
xhr.timeout = 8000;
xhr.onload = () => (xhr.status >= 200 && xhr.status < 300
? resolve(xhr.response)
: reject(new Error(`HTTP ${xhr.status}`)));
xhr.onerror = () => reject(new Error("Network error"));
xhr.ontimeout = () => reject(new Error("Timed out"));
xhr.send();
});
}
async function getPostFetch(id) {
const response = await fetch(`${API}/posts/${id}`, { signal: AbortSignal.timeout(8000) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
const describe = (promise) => promise.then(
(post) => `OK: "${post.title.slice(0, 24)}..."`,
(error) => `Error: ${error.message}`
);
for (const id of [1, 500]) {
const [a, b] = await Promise.all([describe(getPostXhr(id)), describe(getPostFetch(id))]);
const tr = document.createElement("tr");
for (const text of [`/posts/${id}`, a, b]) {
const td = document.createElement("td");
td.textContent = text;
tr.append(td);
}
document.querySelector("#rows").append(tr);
}
</script>
</body>
</html>Both columns agree: /posts/1 gives OK: "sunt aut facere repellat..." and /posts/500 gives Error: HTTP 404. Wrapping XHR in a promise, as getPostXhr() does, is a useful halfway step: callers can use await today, and you swap the inside for fetch() later.
jQuery's $.ajax (legacy)
Many older sites call $.ajax(), which uses XHR underneath. jQuery 4.0 (January 2026) still includes it, though the "slim" build leaves it out.
$.ajax({
url: "/api/marksheets",
method: "POST",
data: formData,
processData: false, // send FormData as it is
contentType: false, // let the browser set the multipart boundary
xhr() {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (e) => updateBar(e.loaded, e.total));
return xhr;
}
})
.done((reply) => showSuccess(reply))
.fail((jqXHR, textStatus) => showError(jqXHR.status, textStatus));Read it this way: done is the success callback, fail the error callback, and the xhr option hands jQuery a custom XHR so the upload can report progress. processData: false and contentType: false are the jQuery way of saying "send this FormData untouched". The old success: and error: options do the same as done and fail. When you remove jQuery from a project, this becomes the plain XHR uploader from Step 4. Learn more in the jQuery course.
Common mistakes
- Adding listeners after
send(). Early events are missed. Attach everything first. - Listening on
xhrfor upload progress. Upload progress fires onxhr.upload; download progress onxhr. - Assuming
loadmeans success. A 404 or 500 also firesload. Checkstatus. - Trusting
responsewithresponseType = "json". Bad JSON givesnull, silently. - Re-enabling buttons only on success. Use
loadend, which fires after success, error, abort and timeout. - Setting
Content-TypeforFormData. As withfetch(), the boundary goes missing.
Interview questions
1. Why would you use XMLHttpRequest instead of fetch today?
Mainly for upload progress, because xhr.upload fires progress events while the body is sent and fetch() has no such event. The other reason is maintaining existing code. For everything else, fetch() with async/await is simpler.
2. What is the difference between xhr.onprogress and xhr.upload.onprogress?
xhr.upload.onprogress reports bytes sent to the server, which is what an upload bar needs. xhr.onprogress reports bytes of the response received. Each event has loaded, total and lengthComputable.
3. What do readyState 4 and status 0 mean together?
The request has finished but no HTTP response arrived: the network failed, CORS blocked it, or it was aborted. A real server answer always has a status such as 200 or 404.
4. Which XHR event always fires at the end?
loadend. It fires after load, error, abort or timeout, so it is the right place to hide spinners and re-enable buttons.
5. How do you convert an XHR timeout to fetch?
Replace xhr.timeout and ontimeout with signal: AbortSignal.timeout(ms) in the fetch options, and check for an error named TimeoutError in the catch block.
Key points
- New code uses
fetch(); XHR remains the tool for upload progress and the code you must maintain. - Order:
new XMLHttpRequest(),open(), setresponseType, headers and listeners, thensend(). xhr.uploadevents report sending; events onxhrreport the response.loadfires for every HTTP status, so checkstatus;status0 means no HTTP answer.loadendalways fires last; use it for clean-up.abort()andtimeoutgive cancel and time limits.- Convert XHR helpers to
fetch()withresponse.ok,AbortSignal.timeout()andasync/await; keep error behaviour the same.
Exercise
Extend the marksheet uploader so a student can choose up to three files at once (multiple, PDF or images only). Upload them one after another, each with its own <progress> bar and status line, and show "All 3 files uploaded" at the end. Refuse any file larger than 5 MB before sending it, and make one Cancel button stop the current upload and skip the rest.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload marksheets</title>
</head>
<body>
<input type="file" id="files" multiple accept=".pdf,image/*">
<button type="button" id="go">Upload</button>
<button type="button" id="cancel">Cancel</button>
<ul id="list"></ul>
<p id="summary" role="status"></p>
<script>
let current = null;
let cancelled = false;
function send(file, bar, line) {
return new Promise((resolve) => {
const xhr = new XMLHttpRequest();
current = xhr;
const data = new FormData();
data.append("marksheet", file, file.name);
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");
xhr.upload.onprogress = (e) => { if (e.lengthComputable) bar.value = e.loaded / e.total; };
xhr.onload = () => { line.textContent = xhr.status < 300 ? `${file.name}: done` : `${file.name}: error ${xhr.status}`; };
xhr.onerror = () => { line.textContent = `${file.name}: network error`; };
xhr.onabort = () => { line.textContent = `${file.name}: cancelled`; };
xhr.onloadend = () => resolve(xhr.status >= 200 && xhr.status < 300);
xhr.send(data);
});
}
document.querySelector("#go").addEventListener("click", async () => {
const files = [...document.querySelector("#files").files].slice(0, 3);
if (files.length === 0) {
document.querySelector("#summary").textContent = "Choose up to three files first.";
return;
}
const list = document.querySelector("#list");
list.replaceChildren();
cancelled = false;
let ok = 0;
for (const file of files) {
const li = document.createElement("li");
const line = document.createElement("span");
const bar = document.createElement("progress");
bar.value = 0;
li.append(bar, " ", line);
list.append(li);
if (cancelled) { line.textContent = `${file.name}: skipped`; continue; }
if (file.size > 5 * 1024 * 1024) { line.textContent = `${file.name}: larger than 5 MB, not sent`; continue; }
if (await send(file, bar, line)) ok++;
}
document.querySelector("#summary").textContent =
ok === files.length ? `All ${ok} files uploaded` : `${ok} of ${files.length} files uploaded`;
});
document.querySelector("#cancel").addEventListener("click", () => {
cancelled = true;
current?.abort();
});
</script>
</body>
</html>Each upload is wrapped in a promise that settles in loadend, so await sends the files one by one. The cancelled flag skips the remaining files after Cancel aborts the current one.
Quick Quiz
1. Where do you listen for progress while a file is being sent to the server?
Upload progress events fire on the XMLHttpRequestUpload object in xhr.upload.
2. An XHR request gets a 404 response. Which event fires?
Any HTTP response fires load; error is only for failures with no response.
3. Which event is the best place to re-enable the Upload button?
loadend fires after success, error, abort and timeout alike.
4. What replaces xhr.timeout = 5000 when you convert to fetch()?
fetch() has no timeout option; a timeout signal aborts it with a TimeoutError.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
