imported>Aeric |
|
(43 intermediate revisions by 2 users not shown) |
Line 1: |
Line 1: |
| ''AJAX'' is the name given to a set of JavaScript functions that let 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. | | The combination of [[JavaScript]] and the platform's [[REST API]]s lets you build a lot of power into a page that displays on a client-side browser. |
|
| |
|
| In fact, an arbitrary string can be passed to or from the server. It's just a matter of having a functions that can deal with the data in the string. The two most popular formats by far, however, are XML and JSON. The platform understands both, so you can choose the flavor you prefer.
| | ====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 [http://www.w3schools.com/ajax/ w3c.schools tutorial]: | | Perhaps the best summary of AJAX comes from the [http://www.w3schools.com/ 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." | | :"AJAX is the art of exchanging data with a server, and updating parts of a web page, without reloading the whole page." |
|
| |
|
| {{Note|When you create a [[Pages|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.}} | | 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.) |
|
| |
|
| ===Basic AJAX Syntax===
| | ''Learn more:'' [https://www.w3schools.com/js/js_ajax_intro.asp AJAX Tutorial] |
| In this syntax description, <tt>xmlhttp</tt> 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="java" enclose="div"> | |
| xmlhttp.open(method, resource_url, async);
| |
| xmlhttp.send(); // GET or DELETE
| |
| xmlhttp.send("request data"); // POST or PUT
| |
| </syntaxhighlight>
| |
|
| |
|
| :where:
| | ====Using AJAX in a Form==== |
| ::* ''method'' is <tt>GET</tt>, <tt>POST</tt>, <tt>PUT</tt>, or <tt>DELETE</tt>
| | The {{^jQuery}} functions included in the platform make it as simple as possible to make an AJAX call. |
| ::* ''resource_url'' is the resource you are accessing
| |
| ::* ''async'' is a boolean.
| |
| :::* If <tt>true</tt>, you put processing code into an <tt>onreadystatechange</tt> 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 <tt>false</tt>, you put processing code after the <tt>send()</tt> statement. (You don't need a function, but the page may appear hang while it is being rendered, so this procedure is not recommended.)
| |
|
| |
|
| :;Considerations:
| | 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 [[REST API:exec Resource|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. |
| :* Most often, you'll want to make asynchronous requests. They're slightly harder to write, because you have to add the <tt>onreadystatechange</tt> function. But the page won't hang while waiting for the server to respond.
| |
| :* The platform's [[REST API]]s 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 [[Specifying_Query_Parameters_in_REST_APIs|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 [http://getfirebug.com/ 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.}}
| | For more information about using AJAX in a form, see the tech community article [https://tech.forums.softwareag.com/t/how-to-invoke-a-class-from-formscript-using-ajax/237541 How to invoke a class from formscript using AJAX]. |
|
| |
|
| ===Example: Retrieving Data with a GET Request === | | ====Using AJAX in a JSP Page==== |
| This example shows AJAX code in a JSP page being used to get login status.
| | When you create a [[Pages|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. |
|
| |
|
| 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.
| | For information on using AJAX in a JSP page, see the tech community article [https://tech.forums.softwareag.com/t/invoking-rest-api-calls-using-ajax-in-agileapps-pages/237543 Invoking REST API Calls using AJAX in AgileApps Pages]. |
|
| |
|
| :<syntaxhighlight lang="java" enclose="div"> | | =====Example: Retrieving Data with a GET Request===== |
| <html> // Note #1
| | To view the example on how to retrieve data using a GET request, see the tech community article [https://tech.forums.softwareag.com/t/retrieving-data-with-a-get-request/237537 Retrieving Data with a GET Request]. |
| <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
| | =====Example: Validating a CSRF session for POST, PUT, and DELETE===== |
| // that runs when a response is received.
| | You have to validate a CSRF session for POST, PUT, and DELETE requests. For information about validating a CSRF session, see the Tech Community article at [https://tech.forums.softwareag.com/t/validating-a-csrf-session-for-post-put-and-delete/237538 Validating a CSRF session for POST, PUT, and DELETE]. This article provides sample codes for validating CSRF sessions for Form Submissions and REST APIs. |
| 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 + ')'); // Note #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"; // Note #3
| |
| async = true;
| |
| xmlhttp.open("GET", resource, async);
| |
| xmlhttp.send();
| |
| }
| |
| </script>
| |
| </head>
| |
|
| |
|
| <body>
| | {{Note|Ensure to add the header X-XSRF-TOKEN with value of xsrfToken from the login response.}} |
| <div id="myDiv"><h2>Click the button to check status.</h2></div>
| |
| <button type="button" onclick="getInfo()">Ok</button>
| |
| </body>
| |
|
| |
|
| </html>
| | =====Example: Retrieving a JSON output of Dynamic Search API on a custom object===== |
| </syntaxhighlight>
| | {{Note| This is applicable only for the legacy UI}} |
| | To retrieve a JSON output of Dynamic Search API on a custom object, refer to this example: |
|
| |
|
| Visiting the page and clicking the button echoes the response returned by server:
| |
| :<syntaxhighlight lang="javascript" enclose="div"> | | :<syntaxhighlight lang="javascript" enclose="div"> |
| {"platform": { // Note #2
| | var recordData = []; |
| "message": {
| | $.ajax({ |
| "code": "0",
| | type: 'GET', |
| "description": "Success"
| | url: '/networking/rest/record/cases?fieldList=subject,description&alt=json', |
| },
| | processData: true, |
| "user": {"is_session_valid": "true"} // Note #4
| | dataType: 'json', |
| }}
| | async:false, |
| | | success: function(data) |
| Result: true
| | { |
| </syntaxhighlight>
| | if (data.platform.record instanceof Array ) |
| | | { |
| ;Notes:
| | recordData = data.platform.record ; |
| :# Although this is a plain HTML page doesn't contain any JSP code, it must have a <tt>.jsp</tt> 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 <tt>eval()</tt> function can be used to turn it into a set of objects, making it easy to retrieve the nested <tt>is_session_valid</tt> value in the next line. | | else if ( typeof data.platform.record != 'undefined' ) |
| :# Here's where we tell the platform to return the data in JSON format.
| |
| :# Here's the value we're interested in. The <tt>is_session_valid</tt> value is in <tt>user</tt>, and <tt>user</tt> is in <tt>platform</tt>. So the path to access it in the code is <tt>platform.user.is_session_valid</tt>.
| |
| | |
| ===POST/PUT Syntax=== | |
| When there is too much data to send using [[Specifying_Query_Parameters_in_REST_APIs|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="java" enclose="div">
| |
| <html>
| |
| <head>
| |
| <script type="text/javascript">
| |
| function createNewCustomer()
| |
| { | | { |
| // Create the communications object.
| | recordData.push(data.platform.record); |
| 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 = "<pre>" + xmlhttp.responseText + "</pre>"; //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.<br/>";
| |
| text += "Record ID: " + reply.platform.message.id;
| |
| }
| |
| else {
| |
| text += "Customer add failed.<br/>";
| |
| text += "HTTP Status = " + xmlhttp.status + "<br/>";
| |
| text += "Platform Status = " + reply.platform.message.code + "<br/>";
| |
| text += reply.platform.message.description;
| |
| }
| |
| }
| |
| document.getElementById("myDiv").innerHTML=text;
| |
| } | | } |
| </script>
| | alert(recordData); |
| </head>
| | } |
| | | }); |
| <body>
| |
| <div id="myDiv"><h2>Click the button to create a new customer.</h2></div>
| |
| <button type="button" onclick="createNewCustomer()">Ok</button>
| |
| </body>
| |
| | |
| </html>
| |
| </syntaxhighlight> | | </syntaxhighlight> |
|
| |
|
| The result of a successful POST looks like this:
| |
| :<syntaxhighlight lang="javascript" enclose="div">
| |
| Customer added successfully.
| |
| Record ID: 313913951
| |
| </syntaxhighlight>
| |
|
| |
| ===Learn More===
| |
| :* AJAX Tutorial: http://www.w3schools.com/ajax/
| |
| <noinclude> | | <noinclude> |
|
| |
| [[Category:Tools and APIs]] | | [[Category:Tools and APIs]] |
| </noinclude> | | </noinclude> |
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.
For more information about using AJAX in a form, see the tech community article How to invoke a class from formscript using AJAX.
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.
For information on using AJAX in a JSP page, see the tech community article Invoking REST API Calls using AJAX in AgileApps Pages.
Example: Retrieving Data with a GET Request
To view the example on how to retrieve data using a GET request, see the tech community article Retrieving Data with a GET Request.
Example: Validating a CSRF session for POST, PUT, and DELETE
You have to validate a CSRF session for POST, PUT, and DELETE requests. For information about validating a CSRF session, see the Tech Community article at Validating a CSRF session for POST, PUT, and DELETE. This article provides sample codes for validating CSRF sessions for Form Submissions and REST APIs.
|
Note: Ensure to add the header X-XSRF-TOKEN with value of xsrfToken from the login response.
|
Example: Retrieving a JSON output of Dynamic Search API on a custom object
|
Note: This is applicable only for the legacy UI
|
To retrieve a JSON output of Dynamic Search API on a custom object, refer to this example:
var recordData = [];
$.ajax({
type: 'GET',
url: '/networking/rest/record/cases?fieldList=subject,description&alt=json',
processData: true,
dataType: 'json',
async:false,
success: function(data)
{
if (data.platform.record instanceof Array )
{
recordData = data.platform.record ;
}
else if ( typeof data.platform.record != 'undefined' )
{
recordData.push(data.platform.record);
}
alert(recordData);
}
});