Practice Set, Week 10, Simple AJAX

by Thomas Smalls

HTML

<h3>Practice Set, Week 10, Simple AJAX</h3>

Complete the JS code to make an AJAX call to the url 'http://courses.dce.harvard.edu/~cscie3/ajax.php' The repsonse will be the JSON string:<br/><pre><code>
    {
    "course":"CSCSI E3",
    "school":"Harvard University Extension",
    "term": "Spring 2015",
    "skills": [
        "programming",
        "javascript",
        "DOM",
        "AJAX",
        "jedi master"
    ]
}
</code></pre>
<p>Your task is to create the event listener that handles the response (readystatechange) for a successful request, converts the response to a JSON object, and outputs the 'school' property value using logMessage(). You may assume that the response will be JSON with the keys noted above (though the values could, of course, be different). </p>

<p>Output will appear below:</p>
<div id="output"></div>

CSS

#output {
    width:80%;
    border: 1px solid black;
    padding: 1em;
}

JavaScript

//  Create the XHR, intitalize the connection with open()) 
//    and send the request. This part is done for you. 
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://courses.dce.harvard.edu/~cscie3/ajax.php"); 
xhr.send();

//  YOUR CODE HERE: Add a readystatechange listener function to respond to the HTTP response
xhr.addEventListener("readystatechange", function(){
  if(this.readyState == 4 && this.status == 200){ 
	  let r = JSON.parse(this.response);
    logMessage(r.school);
    }else{
    console.log(this.readyState);
    console.log(this.status);
    }
})

// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id) {
    if (!id) {
        id = "output";
    }
    document.getElementById(id).innerHTML += msg + "<br>";
}