AJAX and REST
The combination of JavaScript and the platform's REST APIs lets you build a lot of power into a page that displays on a client-side browser.
About AJAX
AJAX is the name given to a set of JavaScript functions that let you connect to a server, get back data, and parse the data into something usable. It originally stood for "Asynchronous JavaScript and XML", but it can also use the JSON format for data interchange.
Perhaps the best summary of AJAX comes from the w3c.schools tutorial:
- "AJAX is the art of exchanging data with a server, and updating parts of a web page, without reloading the whole page."
While an arbitrary string can be passed to or from the server, the two most popular formats by far are XML and JSON. The platform understands both, so you can choose the flavor you prefer. (A common variation is to send XML data to the platform because it's easy to build up strings in XML format, and then get JSON back because that is the easiest format to parse in JavaScript.)
Learn more: AJAX Tutorial
Using AJAX in a Form
The jQuery functions included in the platform make it as simple as possible to make an AJAX call.
The code is expected to be executed as part of a Form, either as part of a Field Script or a Form Script. It builds up an XML string to send to a REST API. In this case, it creates the input XML required by the REST exec API, which executes a method in a Java class. And then tells the API to return JSON, which allows individual elements to be accessed by specifying little more than a JavaScript path.
- <syntaxhighlight lang="javascript" enclose="div">
// Create the structure to send var paramValue = getTextFieldValue(_sdForm, "someField"); var inputXML = "<platform>" + " <execClass>" + " <clazz>com.platform.yourCompany.somePackage.someClass</clazz>" + " <method>someMethod</method>" + " <param1>" + paramValue + "</param1>" + " </execClass>" + "</platform>";
// Use jQuery's ajax method to invoke the REST API $.ajax({ type: 'POST', url: '/networking/rest/class/operation/exec', contentType: 'application/xml', Accept:'application/json', data: inputXML, dataType: 'json', success: function (data) { // Call succeeded. if (data.platform.execClass.someParam) { // Copy data to form fields. setTextFieldValue(_sdForm, "field_name", data.platform.execClass.someParam); } else { alert("No data returned."); } } // End of success function
}); // End of AJAX call
</syntaxhighlight>
- How it works
- _sdForm - A pointer to the current form.
- inputXML - This is the XML structure that will be passed in the call.
- .ajax - The jQuery method to call a web service.
- type - The type of request to make - an http GET or POST.
- url - The URL to access. In the example, a relative URL is specified.
- contentType - The type of data being sent. In this case, the type is XML.
- Accept - The type of data that should be returned. Here, they type is JSON.
- data - The data parameter. On input, pass the inputXML. On output, it contains whatever structure is sent back.
- success - Specifies the function to execute when the call succeeds.
- function - Defines an inline anonymous function (one without a name) that has the code to execute.
- data.platform.execClass.someParam - The exec API returns a structure that is virtually identical to the input structure. Except here, it is in JSON format, which allows individual elements to be accessed by specifying their JavaScript path. So:
- data - The string returned by the call, and passed to the function.
- platform - The root element of the returned structure.
- execClass - The element that contains the key/value pairs that came back
- someParam - A parameter element
- setTextFieldValue - One of the platform's JavaScript Functions, used to set a value in a form.
- alert - Display a message when no data comes back.
Learn more:
- For a fully-workout example, see Java Code Samples#Invoke Web Services Programmatically. The first part creates a class that accesses a web service. The last part uses an AJAX call to invoke that method, using the platform's REST APIs.
Using AJAX in a JSP Page
When you create a Page in the platform, you are creating a JSP page. You can embed Java code in that page, and use it to directly interact with the platform. Or you can use AJAX and the REST APIs, whichever is easiest.
Basic AJAX Syntax
In this syntax description, xmlhttp is the communications object. You'll learn how to make one in the example that follows. For now, the focus is on the methods you use to interact with it.
- <syntaxhighlight lang="javascript" enclose="div">
xmlhttp.open(method, resource_url, async); xmlhttp.send(); // GET or DELETE xmlhttp.send("request data"); // POST or PUT </syntaxhighlight>
- where:
- method is GET, POST, PUT, or DELETE
- resource_url is the resource you are accessing
- async is a boolean.
- If true, you put processing code into an onreadystatechange function, and the page continues displaying itself while the request is being processed. Whenever the response from the server is received, it is integrated into the page. (That is the preferred way to do things.)
- If false, you put processing code after the send() statement. (You don't need a function, but the page may appear to hang while it is being rendered, so this procedure is not recommended.)
- Considerations
- Most often, you'll want to make asynchronous requests. They're slightly harder to write, because you have to add the onreadystatechange function. But the page won't hang while waiting for the server to respond.
- The platform's REST APIs return XML, by default. To get back JSON data, you append "?alt=JSON" to the URL.
- When a resource that responds to a GET request takes additional data, the data is included by appending a query string to the URL, in order to Specify Query Parameters.
- Platform GET (read), PUT (update), and DELETE requests return 200 on success.
- Platform POST (create) requests return 201 on success.
Tip: In Firefox, the Firebug plugin makes it possible to debug JavaScript. You can set breakpoints, see the content of variables, and review the structure of the internal DOM after elements have been dynamically added.
Example: Retrieving Data with a GET Request
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:
- 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.)
- 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.
- A query argument on the URL tells the platform to return the data in JSON format.
- 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.
- <syntaxhighlight lang="javascript" enclose="div">
<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 = "
" + xmlhttp.responseText + "
";
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>
Click the button to check status.
<button type="button" onclick="getInfo()">Ok</button>
</body>
</html> </syntaxhighlight>
Visiting the page and clicking the button echoes the response returned by server:
- <syntaxhighlight lang="javascript" enclose="div">
{"platform": { // #2
"message": { "code": "0", "description": "Success" }, "user": {"is_session_valid": "true"} // #4
}}
Result: true </syntaxhighlight>
POST/PUT Syntax
When there is too much data to send using Query Parameters, a REST API will require you to send the data in a POST request (to add something new) or in a PUT request (to update something existing). You'll specify add a request header that tells the platform what form the data is in:
- <syntaxhighlight lang="java" enclose="div">
xmlhttp.open(method,resource_url,async); xmlhttp.setRequestHeader("Content-type","application/xml"); // or "application/json" xmlhttp.send("request data"); </syntaxhighlight>
Example: Sending Data with a POST Request
This example adds a new entry to the ultra-simple Customers object in the Sample Order Processing System. To keep the example as simple as possible, the data is hard-wired into the script.
- Considerations
-
- In this case, we'll use a synchronous request, because we don't want the rest of the page to render until after the attempted POST has completed.
- A unique key has been defined for the Customer object, so only the first POST should succeed. Subsequent POSTs should fail.
- POST requests return 201 when successful (unlike other REST requests, which return 200).
- <syntaxhighlight lang="javascript" enclose="div">
<html> <head> <script type="text/javascript"> function createNewCustomer() {
// Create the 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"); } // Set up the request to send XML data to the server. // Make it synchronous, so we know how page rendering should proceed async = false; resource = "/networking/rest/record/customer?alt=json"; data = "<platform> \ <record> \ <customer_name>Ian</customer_name> \ <company_address>SoHo</company_address> \ </record> \ </platform>"; xmlhttp.open("POST", resource, async); xmlhttp.setRequestHeader("Content-type", "application/xml"); // or "application/json" xmlhttp.send(data); var text = "";
//text = "
" + xmlhttp.responseText + "
"; //For debugging
// Echo the return value. Success = 201 var reply = eval('(' + xmlhttp.responseText + ')'); if (xmlhttp.readyState==4) { if (xmlhttp.status==201) { text += "Customer added successfully.
"; text += "Record ID: " + reply.platform.message.id; } else { text += "Customer add failed.
"; text += "HTTP Status = " + xmlhttp.status + "
"; text += "Platform Status = " + reply.platform.message.code + "
"; text += reply.platform.message.description; } } document.getElementById("myDiv").innerHTML=text;
} </script> </head>
<body>
Click the button to create a new customer.
<button type="button" onclick="createNewCustomer()">Ok</button>
</body>
</html> </syntaxhighlight>
The result of a successful POST looks like this:
- <syntaxhighlight lang="javascript" enclose="div">
Customer added successfully. Record ID: 313913951 </syntaxhighlight>
Example: Validating a CSRF session for POST, PUT, and DELETE
You have to validate a CSRF session for POST, PUT, and DELETE requests. The following section provides sample codes for validating CSRF sessions for Form Submissions and REST APIs. For both validations, the CSRF cookie name in AgileApps is "XSRF-TOKEN". The validations can be performed using JavaScript or jQuery.
For Forms
- Method 1: Using JavaScript
- To all the existing form fields, add a hidden field having a CSRF token value that is taken from the cookie "XSRF-TOKEN".
- Sample HTML code that you can place inside the form element is as follows:
- <syntaxhighlight lang="javascript" enclose="div">
<input type='hidden' name='X-XSRF-TOKEN' id='X-XSRF-TOKEN' value=></input> </syntaxhighlight>
- Sample code to get the value of "XSRF-TOKEN"
//You can use any approach to get the cookie value. This is an example.
- <syntaxhighlight lang="javascript" enclose="div">
function getCookie(cookieName) { var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) {
var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(cookieName) == 0) {
console.log(c.substring(cookieName.length+1, c.length));
return c.substring(cookieName.length+1, c.length); } } return "";
}
var token = getCookie('XSRF-TOKEN'); </syntaxhighlight>
//assigning value to a hidden element in the form
- <syntaxhighlight lang="javascript" enclose="div">
document.getElementById('X-XSRF-TOKEN').value = token; </syntaxhighlight>
- Method 2: Using jQuery
- <syntaxhighlight lang="javascript" enclose="div">
var token = $.cookie('XSRF-TOKEN');,assign it to the form hidden field $('#X-XSRF-TOKEN').val(token ); </syntaxhighlight>
For REST APIs
Intercept the ajax request and add setrequestheader. The request header is "X-XSRF-TOKEN" and the value for the header is derived from the cookie "XSRF-TOKEN".
- Method 1: Using JavaScript
- <syntaxhighlight lang="javascript" enclose="div">
var send = XMLHttpRequest.prototype.send,
token = getCookie('XSRF-TOKEN') XMLHttpRequest.prototype.send = function(data) { this.setRequestHeader('X-XSRF-TOKEN', token ); return send.apply(this, arguments); };
</syntaxhighlight>
- Method 2: Using jQuery
- <syntaxhighlight lang="javascript" enclose="div">
$.ajax({
type: 'POST', url: domain + url , processData: true, dataType: 'json', beforeSend: function(xhr){ xhr.setRequestHeader('X-XSRF-TOKEN', $.cookie('XSRF-TOKEN')); }, success: function(data) { }
}); </syntaxhighlight>