AJAX is a critical component to creating applications that are highly responsive (performance-wise) in the browser. When you initiate an asynchronous request, the rest of the page is not blocked while some server action is executed. AJAX wrapper classes are built into the Dojo base module, so they’re automatically available to use in XPages. In this post, I’ll show how you can make an AJAX call with Dojo to retrieve data from a REST service in XPages.
Dojo in XPages Series
Dojo in XPages — All Blog Posts
The Test Data and REST Service
I created some test documents that have FirstName, LastName, and Address fields. I created an XPage named REST.xsp and added a REST service (viewJsonService) to provide the data. The pathInfo property of the REST service is set to People, so the URL to reference it from within the same application is REST.xsp/People.
Here is the source of the REST service:
<xe:restService id="restService1" pathInfo="People"> <xe:this.service> <xe:viewJsonService defaultColumns="true" viewName="People"> </xe:viewJsonService> </xe:this.service> </xe:restService>
Here’s what the data looks like when I display it in the browser:
Tip: Remember to always test your REST service output in the browser so you can verify that it’s returning data that you expect.
Retrieving the Data with AJAX
To retrieve that data from another XPage, I can use this dojo code:
// Retrieve data from a REST service and write it out to the console dojo.xhr.get({ url:"REST.xsp/People", handleAs:"json", load: function(data){ for(var i in data){ console.log("#" + i + ": value", data[i]); } } });
XHR is short for XMLHttpRequest — the object that’s used to make an asynchronous request. xhr.get()
is the Dojo wrapper function for making that asynchronous call from client-side JavaScript.
The url
parameter refers to my page with the REST service (including the pathInfo
property that refers to a specific REST service). This can be any URL that you need.
The load
property is a callback function that runs after data has been retrieved. It’s an anonymous function that automatically receives a handle to the data that was retrieved. The parameter name can be whatever you want.
Since the JSON data returned by the REST service is an array of objects, this code loops through the array and prints the retrieved data to the console.
And there you have it – an asynchronous call that retrieves data and writes it out to the console.
In the next post, I’ll dig a little more into the callbacks and demonstrate displaying the returned data on the page.
