XMLHttpRequest
Read legacy XHR code and understand the event model.
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.
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
EasyCheck XHR status
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.