XHR
XMLHttpRequest
An asynchronous HTTP request API. Ajax-based. Being replaced by the Fetch API.
XMLHttpRequest
An asynchronous HTTP request API. Ajax-based. Being replaced by the Fetch API.
XHR (XMLHttpRequest) is an API for performing asynchronous HTTP communication with a server in JavaScript. It was first developed by Microsoft in 1999 for Outlook Web Access and later became a standard in all browsers.
XHR is a core technology of Ajax (Asynchronous JavaScript and XML), which makes it possible to exchange data with a server without reloading the page. It is the technology that enabled interactive web applications of the Web 2.0 era, such as Gmail and Google Maps.
Today the more modern Fetch API is recommended, but XHR is still used for some features, such as progress tracking and request cancellation.
Basic GET request
// Create the XHR object const xhr = new XMLHttpRequest(); // Initialize the request (method, URL, async or not) xhr.open('GET', '/api/users', true); // Handle the response xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); console.log(data); } else { console.error('Request failed:', xhr.status); } } }; // Send the request xhr.send();
POST request (JSON data)
const xhr = new XMLHttpRequest(); xhr.open('POST', '/api/users', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 201) { console.log('Created successfully:', JSON.parse(xhr.response)); } }; const userData = { name: 'John Doe', email: 'hong@example.com' }; xhr.send(JSON.stringify(userData));
File upload and progress tracking
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload', true);
// 업로드 진행률
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
console.log(`업로드: ${percent.toFixed(1)}%`);
}
};
// 완료 처리
xhr.onload = () => console.log('업로드 완료');
xhr.onerror = () => console.error('업로드 실패');
const formData = new FormData();
formData.append('file', fileInput.files[0]);
xhr.send(formData);
Team lead
"This legacy code uses XHR. Do we need to migrate it to Fetch?"
Developer
"Fetch is better for most things, but for showing file upload progress XHR is easier. Fetch doesn't have the upload.onprogress event."
Team lead
"Then let's keep XHR only for the upload part and switch the rest to Fetch."
Understand the readyState values
0: UNSENT, 1: OPENED, 2: HEADERS_RECEIVED, 3: LOADING, 4: DONE. Checking status is meaningful only when readyState is 4.
Avoid synchronous requests
xhr.open(method, url, false) allows a synchronous request, but it blocks the UI, so never use it. Browsers display a warning.
CORS issues
When making requests to a different domain, the server must set CORS headers. With withCredentials = true, requests can also include cookies.