Pure JS XHR example

by ShaikBasha

HTML

<h1>Ajax Exercise</h1>

    <div>
      <button>Load Content</button>
    </div>

    <div class="container">
      <ul id="data">
      </ul>

      <ul id="details">
      </ul>
    </div>

CSS

.container {
  display: flex;
}

JavaScript

// In the index.html file there is a button.  When the button is
// clicked kick off an HTTP GET request to the following URL:
//
//    https://jsonplaceholder.typicode.com/posts
//
// The response text will be a JSON-encoded array of objects.  Inspect
// the response using the browser debugger and then insert the objects
// into the DOM.  Each object in the response should be used to create
// a new <li> element in the existing <ul> container with the id of "data".  
// Display the post title within the <li> element
//
// BONUS #1:
//
// Clicking one of the <li> elements should display all information
// about the clicked post's author (user) in the <ul> with the ID of "details".
// Hint: 
//    make another HTTP request to
//    https://jsonplaceholder.typicode.com/users/{N} 
//    where {N} is the post user_id
//
//
(function() {

  // Your code here.
  
  var buttonEl = document.querySelector('button'),
		dataList = document.getElementById('data'),
		detailsEl = document.getElementById('details');

	buttonEl.addEventListener('click', function(e) {

		var req = new XMLHttpRequest();
		
		req.addEventListener('load', function(e) {
			var data,
				newEl;

			console.log('Response', req.status, req.responseText);
			
			if (req.status == 200) {

				data = JSON.parse(req.responseText);

				for (var i=0; i<data.length; i++) {
					// create new <li>
					newLi = document.createElement('li'); 
					newLi.appendChild(
						document.createTextNode(data[i].title)
					); 

					// could also just use innerHTML to avoid textNode creation 
					//newLi.innerHTML = data[i].name;

					// BONUS #1:
					// Wrapped in IIFE to protect scope and use data[i].id
					(function(id){
						newLi.addEventListener('click', function(e) {
							showDetailsHandler(id);
						});
					})(data[i].userId);

					// @todo
					// BONUS #2
					
					dataList.appendChild(newLi);
				}
			}
		});

		req.open('GET',...