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 trialBrian van Vlymen
12,637 PointsWhy is so imporant put number 4 for simple AJAX I.E. (xhr.readyState === 4) ?
I am not sure strict function have to be "four" where these came from? Is because the letters of getElementById('ajax'); ?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/main.css">
<title>AJAX with JavaScript</title>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'sidebar.html');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
function sendAJAX() {
xhr.send();
document.getElementById('load').style.display = 'none';
}
</script>
</head>
<body>
<div class="grid-container centered">
<div class="grid-100">
<div class="contained">
<div class="grid-100">
<div class="heading">
<h1>Bring on the AJAX</h1>
</div>
<button id="load" onclick="sendAJAX()" class="button">Bring it!</button>
<ul id="ajax">
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
2 Answers
Jonathan Grieve
Treehouse Moderator 91,253 PointsBecause each time you make an AJAX request it has to pass 4 stages. If you get to stage 4 then you've successfully made the request. The code is simply a way to check that we've reached stage for of the ready state. :-)
Jason S
16,247 Points3: processing request the code works if you change the 4 to a 3 so does that mean it works when it's processing?
Jonathan Grieve
Treehouse Moderator 91,253 PointsPersonally I'd still with the 4 because once you get there, you know you've got passed any problems with server or processsing. :-)
Joshua Briley
Courses Plus Student 24,645 PointsI was hoping I wasn't the only one who didn't understand this. Thanks for asking it!
Brian van Vlymen
12,637 PointsBrian van Vlymen
12,637 Pointsthere you go http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
the answer is 4: request finished and response is ready