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 Programming AJAX Processing JSON Data

Robert Bourton
Robert Bourton
6,179 Points

Is this cleaner/easier to read?

I just wanted to rewrite some of the code my way, looking for ways to make it easy to maintain and to update.

How would you rewrite this code in this video?

  • looking for clean code
  • easy to read
  • maintain in the future
  • pure JavaScript
getJSONRequest((html) => {
  const container = document.querySelector('#employeeList')
  container.innerHTML = html
})


function getJSONRequest(cb) {
  const xhr = new XMLHttpRequest()
  let html = '<ul class="bulleted">'

  xhr.onreadystatechange = function () {

    if (xhr.readyState === 4) {
      const employees = JSON.parse(xhr.responseText)

      for ( const employee of employees) {
        html += createHTML(employee.inoffice, employee.name)
      }

      html += '</ul>'
      cb(html)
    }
  }
  xhr.open('GET', 'data/employees.json')
  xhr.send()  
}

function createHTML(inoffice, name) {
  return `<li class=${ inoffice? "in":"out" }> ${name} </li>`
}

Really insane well done !