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):

    <Person>
             <firstName>Rick</firstName>
             <lastName>Delorme</lastName>
             <hairColor>Brown</hairColor>
             <eyeColor>Brown</eyeColor>
     </Person>
  • 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

Events

Description

Onreadystatechange

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

Ontimeout

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

TABLE 3-4 Available methods of the XMLHttpRequest object

Method

Description

Abort

Cancels the current request

getAllResponseHeaders

Gives a complete list of response headers

getResponseHeader

Returns the specific response header

Send

Makes the HTTP request and receives the response

setRequestHeader

Adds a custom HTTP header to the request

Open

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

TABLE 3-5 Available properties of the XMLHttpRequest object

Property

Description

readyState

Gets the current state of the object

Response

Gets the response returned from the server

responseBody

Gets the response body as an array of bytes

responseText

Gets the response body as a string

responseType

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

responseXML

Gets the response body as an XML DOM object

Status

Gets the HTTP status code of the request

statusText

Gets the friendly HTTP text that corresponds with the status

Timeout

Sets the timeout threshold on the request

withCredentials

Specifies whether the request should include user credentials

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

<script>
     $("document").ready(function () {
         $("#btnGetXMLData").click(function () {
                 var xReq = new XMLHttpRequest();
                 xReq.open("GET", "myXMLData.xml", false);
                 xReq.send(null);
                 $("#results").text(xReq.response);
         });
     });
 </script>

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

Parameter

Description

Method

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

URL

The URL to make the request to.

async

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.

Password

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();
xReq.open("GET", "myXMLData.xml", false);
xReq.timeout = 2000;
xReq.ontimeout = function () {
    $("#results").text("Request Timed out");
}
xReq.send(null);
$("#results").text(xReq.response);

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();
xReq.open("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") {
            $("#results").text(xReq.response);
        } else {
            $("#results").text(xReq.statusText);
        }
    }
}
xReq.send(null);

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();
xReq.open("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") {
            $("#results").text(xReq.response);
        } else {
            $("#results").text(xReq.statusText);
        }
    }
}
xReq.send(null);

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