Programming in HTML5 with JavaScript and CSS3: Access and Secure Data

  • 8/25/2014

Objective 3.3: Consume data

This objective covers how to consume data in an HTML5 web application. The ability to consume data from external sources is more popular than ever. Website mash-ups and social integration are major catalysts for this.

Consuming JSON and XML data by using web services

The two data formats commonly used in data transmission are JSON and XML. JSON is unstructured data, whereas XML is structured. JSON uses a special syntax that allows the definition of name value pairs in a lightweight string format. XML, as a relative of HTML, is more structured than JSON with named tags and opening and closing tags. Tags can have attributes. The following are examples of what a person object might look like in both formats where the person object has a first name, last name, hair color, and eye color:

  • JSON:

    {firstName: "Rick", lastName: "Delorme", hairColor: "brown", eyeColor: "brown" }
  • XML (Elements):

  • XML (attributes):

    <Person firstname="Rick" lastName="Delorme" hairColor="Brown" eyeColor="Brown"/>

When publishing data services such as Web Services or a REST API, you can control how you publish the data. When consuming third-party resources, you won’t have control over how they’ve published the data.

Using the XMLHttpRequest object

JavaScript provides built-in support for receiving HTML data via the XMLHttpRequest object. The object makes a call to a web service, REST API, or other data provider services. The advantage of doing this via JavaScript on the client side is to be able to reload portions of the page from an external source without having to post the entire page back to the server.

XMLHttpRequest makes an HTTP request and expects to receive back data in XML format. Both synchronous and asynchronous calls are supported. Table 3-3, Table 3-4, and Table 3-5 list the available events, methods, and properties of the XMLHttpRequest object.

TABLE 3-3 Available events of the XMLHttpRequest object




Sets an event handler for when the state of the request has changed. Used for asynchronous calls.


Sets an event handler for when the request can’t be completed.

TABLE 3-4 Available methods of the XMLHttpRequest object




Cancels the current request


Gives a complete list of response headers


Returns the specific response header


Makes the HTTP request and receives the response


Adds a custom HTTP header to the request


Sets properties for the request such as the URL, a user name, and a password

TABLE 3-5 Available properties of the XMLHttpRequest object




Gets the current state of the object


Gets the response returned from the server


Gets the response body as an array of bytes


Gets the response body as a string


Gets the data type associated with the response, such as blob, text, arraybuffer, or document


Gets the response body as an XML DOM object


Gets the HTTP status code of the request


Gets the friendly HTTP text that corresponds with the status


Sets the timeout threshold on the request


Specifies whether the request should include user credentials

In its simplest form, a request to the server using the XMLHttpRequest object looks like this:

     $("document").ready(function () {
         $("#btnGetXMLData").click(function () {
                 var xReq = new XMLHttpRequest();
       "GET", "myXMLData.xml", false);

This script assumes a button on the HTML form and a div to show the results. A new XMLHttpRequest object is created. The open method is called to specify the request type, URI, and whether to make the call asynchronous. Table 3-6 lists all the parameters to the open method.

TABLE 3-6 Parameters for the XMLHttpRequest open method




The HTTP method being used for the request: GET, POST, etc.


The URL to make the request to.


A Boolean value to indicate whether the call should be made asynchronously. If true, an event handler needs to be set for the onreadystatechanged.

User name

A user name if the destination requires credentials.


A password if the destination requires credentials.

The XMLHttpRequest object provides some mechanisms for handling errors. The most common error to account for is a timeout error. By default, the value of the timeout is zero, which is infinite. A timeout value should always be specified. The code is updated as follows:

var xReq = new XMLHttpRequest();"GET", "myXMLData.xml", false);
xReq.timeout = 2000;
xReq.ontimeout = function () {
    $("#results").text("Request Timed out");

This results in not allowing the call to take any more than two seconds. The timeout is expressed in milliseconds. After the timeout period, the ontimeout event handler is called to allow for this condition to be handled appropriately in the webpage.

An additional consideration for this code is whether to make the call synchronously or asynchronously. Ideally, you should ensure that the call to the service to get the data won’t interfere with users and won’t block them, unless of course they need to wait on the reply before taking any further action. Synchronous calls, as the examples so far have shown, block the user interface while the request is being made. To prevent this, the call should be asynchronous, as shown here:

var XMLHTTPReadyState_COMPLETE = 4;

var xReq = new XMLHttpRequest();"GET", "myXMLData.xml", true);
xReq.timeout = 2000;
xReq.ontimeout = function () {
    $("#results").text("Request Timed out");
xReq.onreadystatechange = function (e) {
    if (xReq.readyState == XMLHTTPReadyState_COMPLETE) {
        if (xReq.status = "200") {
        } else {

The onreadystate event is assigned a function to run when the state of the XMLHttpRequest object is changed. When the request is complete, the readyState changes to complete (readyState == 4). At this point, the HTTP return status can be evaluated for a success value such as 200, and then the processing of the XML data can occur.

The same code that has been used so far to retrieve XML data can also be used to make a request for JSON data. The following update to the code shows this:

var XMLHTTPReadyState_COMPLETE = 4;

var xReq = new XMLHttpRequest();"GET", "myJSONData.json", true);
xReq.timeout = 2000;
xReq.ontimeout = function () {
    $("#results").text("Request Timed out");
xReq.onreadystatechange = function (e) {
    if (xReq.readyState == XMLHTTPReadyState_COMPLETE) {
        if (xReq.status = "200") {
        } else {

The only difference to this code is the name of the URL being passed. In this case, the endpoint is a data source that returns JSON-formatted data instead of XML. The JSON is displayed to the screen in the same way that the XML is displayed.

When the data is received via the XMLHttpRequest object, the data will need to be deserialized into a more user-friendly format. You also might want to submit data to the server in response to user actions. The next objective examines these concepts.

Objective summary

  • JSON and XML are the most common formats used for data exchange.
  • JSON consists of name/value pairs.
  • XML is a structured element-based document.
  • JavaScript provides built-in support for receiving data via the XMLHttpRequest object.

Objective review

  1. Which of the following is a valid JSON string?

    1. {firstName, Rick, lastname, Delorme, hairColor, brown, eyeColor, brown}
    2. {firstName: Rick; lastname: Delorme; hairColor: brown; eyeColor: brown}
    3. {firstName: “Rick”; lastname: “Delorme”; hairColor: “brown”; eyeColor: “brown”}
    4. {firstName: “Rick”, lastname: “Delorme”, hairColor: “brown”, eyeColor: “brown”}
  2. With the XMLHttpRequest object, which of the following properties provides the response in a human readable format?

    1. Response
    2. responseBody
    3. responseText
    4. responseXML
  3. At which stage during an XMLHttpRequest are user credentials sent to the server?

    1. When the connection is opened
    2. When the request is sent
    3. When the ready state is complete
    4. When the server sends a security response requesting the credentials