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 trial
balthazear
5,824 PointsNeed help in explaining in one of Ajax topics - A simple Ajax example
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
From what I understand,
var xhr = new XMLHttpRequest();
The above code is to tell the browser to get ready to use Ajax and need to create new for each request.
Then the part I don't understand,
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
I get why we select id Ajax and the innerHTML part but I don't get the if (xhr.readyState === 4) or why document.getElementById('ajax').innerHTML = xhr.responseText;?
i replayed that part many times but couldn't understand why he used that code? I hope someone can help a beginner to understand whats going on :(
balthazear
5,824 PointsHello thanks for the replies, I finally get whats going on, thank you :)
1 Answer
Steven Parker
243,656 PointsA readyState of 4 indicates successful completion.
Since your handler is triggered on any state change, that test determines that the change that just occurred is a success. Then, you can be confident that the responseText of the xhr now contains the result you want to display. The next line identifies the HTML element on the page that has the ID of "ajax", and uses it to display the result (by assigning it to the element's innerHTML property).
Matija KomorÄec
13,123 PointsMatija KomorÄec
13,123 PointsHi,
so xhr is an object to which you add "onreadystatechange" property to which you assign an anonymous function. And in that function you check if the property on the xhr object called "readyState" is equal to 4, in which case you find the element in the DOM with the ID "ajax" and set its innerHTML to whatever was in the xhr's property called "responseText" (for example "OK" or "Internal Server Error").
Hope that helped, if not, I'll try to be even more detailed.