Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Respond to http request with json object in Liferay Portlet

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.33k
    Comment on it

    Hello Guys

    Ajax known as Asynchronous JavaScript and XML. Ajax based web applications used to send data and retrieve from a server in the background without refreshing complete web page. When we send http request to server from client side using ajax call then server also responded to client with data or confirmation message.

    Here, we are sending JSON data from server side with http response to client.

    See below example to better understand :

    Create resource URL

    <portlet:resourceURL var="ajaxResourceURL" />
    

    Write ajax script

    <script type="text/javascript">
    function _callAjax(val1, val2){
        var url = '<%=ajaxResourceURL %>';    // pass resource URL you created using scriplet / EL.
        jQuery.ajax({
        type : "POST",
        url : url,
        cache:false,
        dataType: "json",
        data: {
          value1: val1,    // extra parameters if you want to pass
          value2: val2
        },    
        success : function(data){
            // do whatever you want with your response data
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
           alert(errorThrown);
           alert(textStatus);
        }
      });
    };
    </script>
    

    Create button in html

    <input type="button" onclick="_callAjax('val1', 'val2')" value="Send" /> 
    

    Create resource method in controller as below :

    @Override
    public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException,IOException {
    
    String value1 = ParamUtil.getString(request , "value1", "default");    // request parameters
    String value2 = ParamUtil.getString(request , "value2", "");
    
    PrintWriter writer = response.getWriter();
    
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(String key, boolean/long/Collection/double/Map/Object value);
    
    writer.write(jsonObject.toString());
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: