Consuming JSON and XML data by using web services



JSON and XML data

There are two data formats commonly used in data transmission:

  • JSON is unstructured data and 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 code demonstrates the XML and JSON data:

   JSON:
    {firstName: "John", lastName: "Codew", hairColor: "brown", eyeColor: "brown" }
    XML (Elements):
    <Person>
        <firstName>John</firstName>
        <lastName>Codew</lastName>
        <hairColor>Brown</hairColor>
        <eyeColor>Brown</eyeColor>
    </Person>
    XML (attributes):
    <Person firstname="John" lastname="Codew" haircolor="Brown" eyecolor="Brown"/>

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. In this way the object is 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.

The following Table list the 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.

The following Table list the available methods of the XMLHttpRequest object.

Methods 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

The following Table list the available properties of the XMLHttpRequest object.

Properties 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

Request to the server using the XMLHttpRequst Object

You can make server request using the XMLHttpRequst Object by:

  • using GET to obtain data from the server
  • using POST to send data to the server

The following code demonstrates a server request to the server:

<body>
<div>
    <button type="button" id="load-data" class="btn">Get XML Data Async</button>
    <div id="output"></div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $('#load-data').click(function () {
        var xhr = new XMLHttpRequest();
        //WHEN WE GET DATA
        xhr.onreadystatechange = function () {
            //MAKE SURE WE HAVE DATA
            // 4 - data are ready      200 - completed
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = xhr.response;
                $('#output').text(data);
            }
        }
        //OPEN CONNECTION
        xhr.open('GET', 'myXMLData.xml');
        //SEND THE REQUST
        xhr.send();
    });
</script>
</body>

When making a server request a A new XMLHttpRequest object is created. The open method is called to specify the request type, URI, and whether to make the call asynchronous.

The Table below lists all the parameters to the open method.

Prameter 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

Handling errors using XMLHttpRequest object

The XMLHttpRequest object provides some mechanisms for handling errors. The most common error to account for is a timeout error.

Handling error in this way you need:

  • to specify a timeout value in milliseconds
  • to make asynchronous call to the server

The following code handles errors by making an asynchronous call for Json data:

<body>
<button id="btnGetJSONData">Get JSON Data Async</button>
<div id="results"></div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $("document").ready(function () {
        $("#btnGetJSONData").click(function () {
            try {
                //status completed
                var XMLHTTPReadyState_COMPLETE = 4;
                var xReq = new XMLHttpRequest();
                //async call to the server
                xReq.open("GET", "MyJsonData.json", false);
                xReq.timeout = 2000;
                xReq.ontimeout = function () {
                    $("#results").text("Request Timed out");
                }
                xReq.onreadystatechange = function (e) {
                    if (xReq.readyState == XMLHTTPReadyState_COMPLETE) {
                        //status with success
                        if (xReq.status = "200") {
                            $("#results").text(xReq.response);
                        } else {
                            $("#results").text(xReq.statusText);
                        }
                    }
                }
                xReq.send(null);
            } catch (e) {
                alert(e.message);
            }
        });
    });
</script>
</body>

Ads Right