Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialChris Reich
15,163 PointsWhat does xhr.readyState === 4 mean in the code below? Why 4?
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'sidebar.html');
function sendAJAX() {
xhr.send();
document.getElementById('load').style.display = "none";
}
4 Answers
jason chan
31,009 PointsreadyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
Abhishek Bhardwaj
3,316 PointsAs Jason chan wrote request check the condion from 0 to 4 and 4th states define the download state means 'request finished and response is ready' readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4: 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready
David Weigel
8,265 PointsTo add to the information from Jason - a readyState of 4 means that the program has "heard" back from the server. You want to wait for this (hence the if statement) before executing anything further.
Full documention from MDN: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
NiKole Maxwell
11,083 PointsI actually found the info page on W3 useful for this question as well. https://www.w3schools.com/xml/ajax_xmlhttprequest_create.asp