AJAX & Async Requests·AJAX from first request to live updates

XMLHttpRequest

Read legacy XHR code and understand the event model.

Beginner 12 min read Lesson 2 of 300 Challenge included
What you will be able to do
  • readyState 4 means done.
  • Check xhr.status, not just onload.
  • Use xhr.upload for progress events.
  • Prefer fetch for new code.

In plain English

XMLHttpRequest is the original AJAX API. It uses events and readyState transitions. Modern code should use fetch, but legacy code and file upload progress still use XHR.

xhr.jsJavaScript
const xhr = new XMLHttpRequest()
xhr.open('GET', '/api/lessons')
xhr.onload = () => {
  if (xhr.status >= 200 && xhr.status < 300) console.log(JSON.parse(xhr.responseText))
  else console.error('HTTP', xhr.status)
}
xhr.onerror = () => console.error('Network error')
xhr.send()
Your turn

Check XHR status

Easy

Log an error when xhr.status is 500 in onload.

JAVASCRIPT · starter
xhr.onload = () => { }
Check your understanding before moving on.
Knowledge checkQuestion 1

Which readyState value means the request is complete?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: fetch
Lesson 2 of 300 · 0% of course