Liferay jQuery Ajax examples


Liferay jQuery Ajax examples

you can go through the “Liferay AUI Ajax examples” tutorial to see Liferay AUI ajax sample code to load JSON data dynamically, but this tutorial will provide sample jQuery Ajax example code to set JSON reponse to aui select element.

  • Create Service Resource method to generate JSON list
  • Invoke Service Resource method using jQuery AJAX

    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. JQuery AJAX snippet

  • Define resource url request and set the data parameters as request parameters unlike aui-io-request. some times, jQuery data may not work.so try to create ajax url by appending parameters like below
    • var catUrl = ${baseResourceUrl}+”&<portlet:namespace>cmd=getCategories”;
<portlet:resourceURL var="baseResourceUrl" ></portlet:resourceURL>
<aui:form>
    <aui:select name="categories">
    </aui:select>
</aui:form>
<aui:script>

   var catUrl = ${baseResourceUrl}+"&<portlet:namespace>cmd=getCategories";
   jQuery.ajax({
          url:catUrl,
          type:"POST",
          dataType:"json",
           async:false,
           cache:false,
           success:function(data,textStatus, XMLHttpRequest){
               if (data.length === 0) {
                  $("#error").empty();
                  $("#error").html("No Categories found");
                  $("#error").addClass("alert");
                }
               else {
                  $.each(data, function(index, value) {
                 $("#<portlet:namespace/>categories").append('<option value="'+value.id+'">' + value.name+ '</option>');
            }); 
           },
            error:function(data,textStatus, XMLHttpRequest){
              alert("request failed");
          }
   });        

<aui:script>