Send asynchronous browser requests with fetch, XMLHttpRequest, JSON, errors, and progressive UI.
Lessons
Track request progress through ready states.
readyState & Events is easiest to learn by reading the example, changing it, and observing the result.
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/lessons');
xhr.onreadystatechange = function () {
// readyState 4 = DONE
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error('Error', xhr.status);
}
}
};
xhr.send();Practice the readyState & Events example in a small scratch file, then explain what changed and why.