HowTo:Use AJAX and REST in a Web Page to GET data

From LongJump Support Wiki

For:   Designers
Level: Advanced
Time: 15 minutes

See more:
    ◾ HowTo Guides

This example shows AJAX code in a JSP page being used to get login status.

Of course, the example is trivial, since login status will always be "true". (Otherwise, you couldn't see the page at all.) But even this simple example displays a number of interesting characteristics, called out in the code that follows:

  1. Although this is a plain HTML page that doesn't contain any JSP code, it must have a .jsp extension, to be stored on the platform. (JSP code can then be added whenever desired.)
  2. As shown by the sample response, the data is returned in JSON format. That format works well in JavaScript, because the eval() function can be used to turn it into a set of objects, making it easy to retrieve the nested is_session_valid value in the next line.
  3. A query argument on the URL tells the platform to return the data in JSON format.
  4. The value we're interested in is contained in the JSON data. The is_session_valid value is in user, and user is in platform. So the path to access it that value is platform.user.is_session_valid.
<html>                                                           // #1
<head>
<script type="text/javascript">
function getInfo()
{
    // Create a communications object.
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    // Configure the comms object with the function
    // that runs when a response is received.
    xmlhttp.onreadystatechange=function() {                       
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // Success. Insert returned data into the page.
            text = "<pre>" + xmlhttp.responseText + "</pre>";
            var reply = eval('(' + xmlhttp.responseText + ')');  // #2
            result = reply.platform.user.is_session_valid;       
            text += "Result: " + result;
            document.getElementById("myDiv").innerHTML=text;
        }
    }
    
    // Set up the request and send it to the server
    resource = "/networking/rest/user/isSessionValid?alt=json";  // #3
    async = true;
    xmlhttp.open("GET", resource, async);    
    xmlhttp.send();               
}
</script>
</head>

<body>
    <div id="myDiv"><h2>Click the button to check status.</h2></div>
    <button type="button" onclick="getInfo()">Ok</button>
</body>

</html>

Visiting the page and clicking the button echoes the response returned by server:

{"platform": {                                                   // #2
  "message": {
    "code": "0",
    "description": "Success"
  },
  "user": {"is_session_valid": "true"}                           // #4
}}

Result: true

Learn more: Basic AJAX Syntax