XMLHttpRequest and Ajax

  1. Background
    1. Most modern websites and web application use Ajax to load small changes to a web page instead of loading an entirely new web page
    2. Ajax is a group of interrelated web development techniques that allow websites to be more responsive to the user
      1. Asynchronous - web page can submit data to and retrieve data from the web server in the background while the user continues to interact with the web page
      2. JavaScript - All communication between web page and web server is handled by JavaScript using the XMLHttpRequest object
      3. XML - Ajax can use XML, but it is not required. JSON is more often used than XML.
    3. The term Ajax was coined in 2005 by Jesse James Garrett
    4. The XMLHttpRequest object was introduced by Microsoft in 1998
  2. Asynchronous request
    1. Example uses XMLHttpRequest to make an asynchronous request to datetime.php
      function getDateTime() {
      	// Create the XMLHttpRequest 
      	var xhr = new XMLHttpRequest();
      
      	// Create load event handler
      	xhr.addEventListener("load", responseReceived);
      
      	// Initialize an HTTP GET request 
      	xhr.open("GET", "/~fmccown/datetime.php"); 
      	
      	// Send the request asynchronously
      	xhr.send();
      }
      
      1. load event handler is called when the response is received (shown later in the notes)
      2. open(requestMethod, URL) - setup an http request using the requestMethod (GET or POST) to the given URL
      3. send(postString) - make the http request passing the postString if using POST or nothing for GET
      4. datetime.php returns back the current date and time on the web server
    2. Example load event handler (or callback)
      function responseReceived() {
      	// Put the text from Taz into the web page's span
      	if (this.status == 200) {
      		document.getElementById("datetime").innerHTML =	this.responseText;
      	}
      	else {
      		document.getElementById("datetime").innerHTML = "Unable to obtain the date/time.";
      	}
      }
      
      1. responseReceived() is called automatically when the http response is received
      2. this - object that refers to the XMLHttpRequest object that made the request
      3. status - http status code of the response (200, 404, etc.)
      4. responseText - entire response body
    3. Example triggering the Ajax code
      <input type="button" value="Get Date/Time on Web Server" onclick="getDateTime()">
      <span id="datetime"></span>
      
    4. Open Chrome dev tools and check Network tab to see datetime.php request
  3. Parsing JSON
    1. In previous examples a text string was returned by datetime.php, but the server can respond with XML or JSON
    2. JavaScript Object Notation (JSON) is a structured format for data based on a subset of the JavaScript language
    3. datetimejson.php responds with JSON
      {"year":"2017","month":"11","day":"27","hour":"14","minute":"50","second":"17"}
      
    4. When responseType is set to "json", the HTTP response text is expected to be JSON; the JSON is parsed, and response is assigned a JavaScript object containing the data
      function getDateTime() {
      	var xhr = new XMLHttpRequest();
      	xhr.addEventListener("load", responseReceived);
      	xhr.responseType = "json";
      	xhr.open("GET", "/~fmccown/datetimejson.php");
      	xhr.send();
      }
      
      function responseReceived() {
      	if (this.status === 200) {
      		// JSON converted into JavaScript object this.response
      		console.log("year = " + this.response.year);
      		console.log("time = " + this.response.hour + ":" + this.response.minute + 
      			":" + this.response.second);		
      	}
      	else {
      		console.log("Unable to contact datetimejson.php");
      	}
      }
      
  4. Limitations
    1. For security purposes, the URL used in open() are subject to the same origin policy meaning the URL must point to the same web server from which the JavaScript code originated
      // Error if JS is from http://www.harding.edu!
      asyncRequest.open("GET", "http://otherwebsite.com/"); 	
      
    2. Three ways around same origin limitations:
      1. Cross-Origin Resource Sharing (CORS)
      2. JSONP
      3. Proxy server
    3. What if the web server needs to transmit a message to the client?
      1. XMLHttpRequest object only allows the client to initiate communication with the web server, but the server cannot initiate communication with the client.
      2. Client could use polling to periodically make requests to the server asking if updates are available
      3. Server-sent events - Allows the web server to transmit a message to the browser when needed
      4. WebSockets - Allows communication back and forth between client and server at any time, but takes more network resources