Retrieving Data with a GET Request

This example shows AJAX code in a JSP page that is used to get the login status.

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 does not contain any JSP code, it must have a .jsp extension, to be stored in the platform.  The JSP code can be added at a later stage, whenever required.
  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 are 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 the 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) {
        xmlhttp=new XMLHttpRequest();
    }

    // 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