🏠 Home / Hub

📡 JSON & AJAX Lesson 05 — XMLHttpRequest (Legacy AJAX)

← Back to JSON Menu  |  🏠 Hub

1. AJAX ဆိုတာ

AJAX = Asynchronous JavaScript And XML
Page reload မလုပ်ဘဲ server နဲ့ data exchange လုပ်တဲ့ technique
2005 ကတည်းက ရှိပြီ — Google Maps, Gmail ကနေ popularize ဖြစ်
XMLHttpRequest (XHR)Fetch API
Year1999 (IE 5)2015 (modern)
SyntaxVerbose, callbackClean, Promise-based
Progress✅ onprogress event❌ (ReadableStream)
Abort✅ xhr.abort()✅ AbortController
IE support✅ All versions❌ IE 11 needs polyfill
RecommendLegacy code only✅ Use for new projects
⚠️ New projects မှာ Fetch API ကို သုံးပါ — XHR ကို old code maintenance ဖတ်ဖို့ပဲ လိုတယ်

2. XHR Basic Usage

// 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();

3. XHR POST Request

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
}));

4. XHR Progress Event — File Upload

// 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
💡 File upload with progress bar → XHR ဒဲ့ case ကနေ ကောင်းတုန်း! Fetch version = verbose

5. jQuery $.ajax (Legacy Framework)

// 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 →

📌 Study Checklist