| XMLHttpRequest (XHR) | Fetch API | |
|---|---|---|
| Year | 1999 (IE 5) | 2015 (modern) |
| Syntax | Verbose, callback | Clean, Promise-based |
| Progress | ✅ onprogress event | ❌ (ReadableStream) |
| Abort | ✅ xhr.abort() | ✅ AbortController |
| IE support | ✅ All versions | ❌ IE 11 needs polyfill |
| Recommend | Legacy code only | ✅ Use for new projects |
// XHR readyState values:
// 0 = UNSENT (open မခေါ်ရသေး)
// 1 = OPENED (open() ခေါ်ပြီး)
// 2 = HEADERS_RECEIVED (response headers ရပြီး)
// 3 = LOADING (body loading)
// 4 = DONE (complete)
const xhr = new XMLHttpRequest();
// 1. Configure request
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
// 2. Set response type
xhr.responseType = 'json'; // auto parse JSON
// 3. Event handlers
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // DONE
if (xhr.status === 200) {
console.log(xhr.response); // parsed object (responseType = 'json')
console.log(xhr.response.name);
} else {
console.error('Error:', xhr.status);
}
}
};
// Shorter: onload / onerror
xhr.onload = function() {
if (xhr.status === 200) console.log(xhr.response);
};
xhr.onerror = function() {
console.error('Network error');
};
// 4. Send request
xhr.send();
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status === 201) { // Created
console.log('Created:', xhr.response);
}
};
xhr.send(JSON.stringify({
title: 'My Post',
body: 'Post content',
userId: 1
}));
// XHR ၏ unique advantage = upload/download progress tracking
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload');
// Upload progress
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
document.getElementById('progress').style.width = percent + '%';
document.getElementById('percent').textContent = percent + '%';
}
};
// Download progress
xhr.onprogress = function(event) {
if (event.lengthComputable) {
const percent = (event.loaded / event.total * 100).toFixed(1);
console.log(`Downloaded: ${percent}%`);
}
};
xhr.onload = () => console.log('Upload complete!');
xhr.onerror = () => console.error('Upload failed');
const formData = new FormData();
formData.append('file', fileInput.files[0]);
xhr.send(formData);
// Note: Fetch API + ReadableStream can do this too, but XHR is simpler for progress
// jQuery AJAX (ဟောင်းတဲ့ project တွေမှာ ဆက်ဖတ်ရ)
// <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
// GET
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users/1',
method: 'GET',
success: function(data) {
console.log(data.name);
},
error: function(xhr, status, err) {
console.error(err);
}
});
// Shorthand
$.get('/api/users', function(data) { console.log(data); });
$.post('/api/users', { name: 'Ko' }, function(res) { console.log(res); });
// Modern jQuery (returns Promise)
$.ajax({ url: '/api/users', method: 'GET' })
.done(data => console.log(data))
.fail(err => console.error(err));
// OR with then()
const users = await $.ajax({ url: '/api/users' });
// ⚠️ New projects မှာ jQuery မသုံးပါနဲ့ — Fetch API ပြောင်းပါ
← JSON 04 | Next: JSON 06 → Real API Examples →