How to pass data from page to Portlet class through AJAX call?

2.3k views Asked by At

I'm trying to pass a value in an AJAX 'GET' request to my Portlet class, but I can't quite figure out a way to access such variable's value in the class. My AJAX code is:

function loadXMLDoc() 
{           
   var nocache = new Date().getTime();
   var xmlhttp=new XMLHttpRequest();
   var url = "${mURL}";
   url += '?cache=' + nocache + '&nRows=' + numberOfRows;   // Generate unique request URL
   xmlhttp.open("GET", url,true);
   xmlhttp.onreadystatechange = function()
   {        
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      { 
          document.getElementById("contentContainer").innerHTML= xmlhttp.responseText;
      } 
   }    
   xmlhttp.send();
}

Where 'nRows' is the variable I am trying to pass to my Portlet class. The part of my portlet class where I attempt to retrieve the variable's value is:

@Override
 public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException,IOException
 {                      
     /* Returns null */
     String nRows = request.getParameter("nRows");

     response.setContentType("text");           
     response.resetBuffer();
     String htmlContent = htmlInterpreter.getParsedHTML();
     response.getWriter().print(htmlContent);
     response.flushBuffer();                                 
 }

Any ideas about alternatives to access the value of 'nRows' in the serveResource(...) method? Thanks in advance!

1

There are 1 answers

0
Ranjitsinh On BEST ANSWER

I recommend to use liferay's <portlet:resourceURL var="resourceURL"> </portlet:resourceURL> with AlloyUI instead of using simple xmlhttp function.

Change required namespace parameter in your liferay-portlet.xml

<requires-namespaced-parameters>false</requires-namespaced-parameters>

Add following import

    <%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
<portlet:defineObjects />

Change the url to below

url += '?cache=' + nocache + '&<portlet:namespace/>nRows=' + numberOfRows; 

Please find below code to get a parameter using ParamUtil:

@Override
 public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException,IOException
 {                      
     /* Returns null */
     String nRows = ParamUtil.getString(resourceRequest, "nRows");

     response.setContentType("text");           
     response.resetBuffer();
     String htmlContent = htmlInterpreter.getParsedHTML();
     response.getWriter().print(htmlContent);
     response.flushBuffer();                                 
 }

For more details put your eyes on this link:

http://liferayway.blogspot.in/2013/08/ajaxjsonliferay-example.html

Hope it may help you.!!