RE: Liferay 7.2 - Call portlet method from javascript

Fabio Carvalho, modified 6 Years ago. Junior Member Posts: 81 Join Date: 6/25/19 Recent Posts
Hi,

I am trying the date range picker and I have the following code in my view.jsp:
<input type="text" id="daterange" />
<script>
        $(function () {
                $('#daterange').daterangepicker({
                        startDate: moment().subtract(7, "days"),
                        endDate: moment(),
                        locale: {
                                "format": "DD/MM/YYYY",
                                "separator": " - "
                        },
                }, function (start, end) {
                        alert("New date range selected: '" + start + "' to '" + end + "'");
                });
    
                $('#daterange').on('apply.daterangepicker')
        });
</script>

Until now its working ok! I reach the alert with the start and end values that I selected. Now I want to call and pass those values to a Java method that I have on my portlet:
public void filterByDate(ActionRequest request, ActionResponse response) {
        System.out.println("SUCCESS");
}

What would be the correct aproach for this?
thumbnail
Mohammed yasin, modified 6 Years ago. Liferay Master Posts: 593 Join Date: 8/8/14 Recent Posts
Hi, 
  You can do ajax call to portlet from javscript to pass the data from javascript to Java class. 

  For this you can create a resource url , and call the  serveResource method of portlet or MVC Resource command.

You can refer below link 
https://portal.liferay.dev/docs/7-1/tutorials/-/knowledge_base/t/mvc-resource-command
Fabio Carvalho, modified 6 Years ago. Junior Member Posts: 81 Join Date: 6/25/19 Recent Posts
Hi Mohammed,

Your method works! For future reference let me show what I did exactly. I added the ajax call to my function:
<portlet:defineObjects />
<portlet:resourceURL var="filterURL" />

<input type="text" id="daterange" />
<script>
$(function () {
$('#daterange').daterangepicker({
startDate: moment().subtract(7, "days"),
endDate: moment(),
locale: {
"format": "DD/MM/YYYY",
"separator": " - "
},
}, function (start, end) {
$.ajax({
url : '${filterURL}',
type : 'POST',
data : {
"<portlet:namespace/>start": start.toString(),
"<portlet:namespace/>end": end.toString()
}
});
});

$('#daterange').on('apply.daterangepicker')
});
</script>


And in my java class I added the serveResource method:
@Override
public void serveResource(ResourceRequest request, ResourceResponse response) throws IOException, PortletException {
System.out.println(ParamUtil.getString(request, "start"));
super.serveResource(request, response);
}