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

From AgileApps Support Wiki
Revision as of 20:29, 31 January 2012 by imported>Aeric

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:

  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. Here's where we tell the platform to return the data in JSON format.
  4. Here's the value we're interested in. The is_session_valid value is in user, and user is in platform. So the path to access it in the code 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