JavaScript AJAX Basics (retiring) Programming AJAX Stage 2 Challenge

Code where art thou ?

var xhrRoom = new XMLHttpRequest(); //step 1:
xhrRoom.onreadystatechange = function () {
  if(xhrRoom.readyState === 4 && xhrRoom.status === 200) {
    var rooms = JSON.parse(xhrRoom.responseText);
    var roomsHTML ='<ul class="rooms">';

    for (var i=0; rooms.length; i+=1){
      if (rooms[i].available === true){
        roomsHTML += '<li class="empty">';
      }else {
        roomsHTML += '<li class="full">';
      roomsHTML += rooms[i].room;
      roomsHTML += '</li>';

    statusHTML += '</ul>';
    document.getElementById('roomList').innerHTML = roomsHTML;
  } // step 2:
};'GET','../data/rooms.json'); //step 3
xhrRoom.send(); // step 4


Here is my code. When i preview it, nothing is showing. I checked the console and i get the following error: "Uncaught TypeError: Cannot read property 'available' of undefined". There seems to be something wrong with the way my object's value keys are being accessed ? Any feed back is greatly appreciated !

2 Answers

Nico Trivelli
Nico Trivelli
20,359 Points

Hi Amir Bizimana ,

Only a couple of things that I noticed there that hopefully can be of help.

Your counter i in the for loop is not included with the length of rooms appropriately.

It should be:

    var i = 0; i < rooms.length; i+= 1

Also, when you closed the <ul> tag, you accidentally added it to a variable statusHTML, rather than to roomsHTML.


Hey Nico Trivelli, thanks so much for spotting the mistakes ! The code works perfect now !

Nico Trivelli
Nico Trivelli
20,359 Points

No problem.

Glad it worked!