Liferay AUI Ajax examples


Liferay AUI Ajax examples

Applications requires to load JSON data into html select options. In Liferay we can use aui-io-request to process ajax calls. In this tutorial, we will sample example to create select element from JSON dynamically.

  • Create Service Resource method to generate JSON list
  • Invoke Service Resource method using Liferay aui-io-request
  • we can use jQuery Ajax also to call Liferay service resource method.

    Create a JSON object in service resource method

In this, Use  JSONFactoryUtil.createJSONObject() to create JSON Objects in Liferay and set the JSON object to response writer.

 public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException,
 PortletException {
 String cmd = ParamUtil.getString(resourceRequest,"cmd");
 if("getCategories".equalsIgnoreCase(cmd))
 { 
      List<Category> catList = CategoryLocalServiceUtil.getAllCategories();
       JSONArray catListJson = JSONFactoryUtil.createJSONArray();
        for (Category cat : catListJson)
       { 
          JSONObject catJSON = JSONFactoryUtil.createJSONObject();
          catJSON.put("id", cat.getId());
          catJSON.put("name", kpi.getName());
         catListJson.put(catJSON); 
      }
       resourceResponse.getWriter().print(catListJson.toString()); 
  } 
 }
  1. Client side AUI script

  • define resource url request
  • set the parameters prefixed with portlet name in data field
    • data: {
      <portlet:namespace/>cmd: ‘getCategories’,                                                                                                                <portlet:namespace/>id: 101,’                                                                                                               <portlet:namespace/>value: ”test”
      },

 

<portlet:resourceURL var="baseResourceUrl" ></portlet:resourceURL>
<aui:form>
    <aui:select name="categories">
    </aui:select>
</aui:form>
<aui:script>
AUI().use('aui-io-request', function(A){
        A.io.request('${baseResourceUrl}', {
            method: 'post', 
            sync: true,
            data: {
                <portlet:namespace/>cmd: 'getCategories' 
              },
            on: {
                success: function() { 
            },
            end: function(){ 
                 var catList = JSON.parse(this.get('responseData'));
                 if (catList.length === 0) {
                           $("#error").empty();
                           $("#error").html("No Categories found");
                           $("#error").addClass("alert");
                  }
                 else {
                       $.each(catList, function(index, value) {
                      $("#<portlet:namespace/>categories").append('<option value="'+value.id+'">' + value.name+ '</option>');
                 }); 
       }
   }
 }
 });
 });
<aui:script>

 

Thats it . you can see

Comments are closed.