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

JavaScript AJAX Basics (retiring) Programming AJAX Stage 2 Challenge Answer

Ana Luiza Barreto Marinho
Ana Luiza Barreto Marinho
2,210 Points

This is how I solved it

// Grab Divs and create <ul class="rooms"></ul>
const roomListDiv = document.getElementById('roomList');
const roomStatus = document.createElement('ul');
roomStatus.className = 'rooms';
let roomStatusItem;

// Create XMLHttpRequest Object
const roomsAv = new XMLHttpRequest();

// A create element function, so I don't repeat myself
let createElement = (el, cssClass) => {
    roomStatusItem = document.createElement(el);
    roomStatusItem.className = cssClass;
    roomStatus.appendChild(roomStatusItem);
};

// And this is pretty much what Dave did:
roomsAv.onreadystatechange = () => {
  if(roomsAv.readyState === 4 && roomsAv.status === 200) {
    let rooms = JSON.parse(roomsAv.responseText);
    for (let i = 0; i < rooms.length; i+= 1) {
// check if rooms are available
      if(rooms[i].available === true) {
// if so create a li with the class of empty
        createElement('li', 'empty');
      } else {
// if not create a li with the class of full
        createElement('li', 'full');
      }
// append room numbers to tags
      roomStatusItem.textContent = rooms[i].room;
    }
/* now because I created the element using js instead of just putting the html tag, instead of adding innerHTML, I appended the room status */
      roomListDiv.appendChild(roomStatus);
// check if there are no errors
  } else if (roomsAv.status === 404) {
    roomListDiv.textContent = 'Could not find rooms avaibility list. Check with your provider if the database is down';
  } else if (roomsAv.status === 401) {
      roomListDiv.textContent = 'Unothorized access. Contact if your provider to check your credentials';
  }
};

// done :D
roomsAv.open('GET', 'data/rooms.json');
roomsAv.send();
Rekk Msaknee
Rekk Msaknee
Courses Plus Student 212 Points

Interesting approach there with using functions to create elements

1 Answer

Muhammad Umar
Muhammad Umar
7,817 Points

Awesome! Thank you for sharing.