Week 10 Assignment 3

by Keeley Peck

HTML

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

<p>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>
<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' proerty 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>
<div id="putItHere"></div>

CSS

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

JavaScript

var el = document.getElementById("output");

//  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", "http://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(){
//  Check here for new state and HTTP response code
//   and write the response to the DIV
    if(this.readyState == 4 && this.status == 200){
         el.innerHTML = this.response;   
    }
});

// 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>";
}