Monday 12 September 2016

Passing form in ajax call


Submit HTML form with AUI Ajax

In case if you wish to pass html form with aui ajax, you need to change view.jsp code as per below snippet


<portlet:resourceURL var="testAjaxResourceUrl"></portlet:resourceURL>

<form id="testAjaxForm" action="">
    <input type="text" name="<portlet:namespace />param2">
    <input type="button" value="Submit" onclick="ajaxCall()">
</form>

<script type="text/javascript">
function ajaxCall(){
    AUI().use('aui-io-request', function(A){
        A.io.request('${testAjaxResourceUrl}', {
               method: 'post',

               data: {

                   <portlet:namespace />sampleParam: 'value2',
               },
               form:{
                   id:'testAjaxForm'
               },
               on: {
                       success: function() {
                        alert(this.get('responseData'));
                   }
              }
        });
    });
}
</script> 


package com.opensource.techblog.portlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class TestAjaxPortlet extends MVCPortlet {

    private static Log _log = LogFactoryUtil.getLog(TestAjaxPortlet.class.getName());
   
    @Override
    public void serveResource(ResourceRequest resourceRequest,
            ResourceResponse resourceResponse) throws IOException,
            PortletException {
       
        String param = ParamUtil.get(resourceRequest, "param2", StringPool.BLANK);
       
        _log.info("Parameter is ==>" + param);
       
        resourceResponse.setContentType("text/html");
        PrintWriter out = resourceResponse.getWriter();
        out.print("You have entered ==>"+param);
        _log.info("Ajax call is performed");
        out.flush();
        super.serveResource(resourceRequest, resourceResponse);
    }
}
 















We can pass whole form in ajax call by serializing the form

In your script:

var str = $('#<portlet:namespace/>jobform').serialize();
$.ajax({
 type: "post",
 data: str,
 dataType: 'text',
 url: "<%=submitJobURL%>",
 async: false,
 success: function(data) {
  alert("success");
 }
});

And your form view in jsp:
<aui:form method="post" name="jobform">
<aui:input name="jobName" type="text" />
</aui:form>

Here jobform is your form id.

And we can get values in controller by normal way

String jobName = ParamUtil.getString(request,"jobName");

Thanks,
K.Mufas Mohammed Mydeen

No comments:

Post a Comment