Showing posts with label ajax call using serve resource in liferay. Show all posts
Showing posts with label ajax call using serve resource in liferay. Show all posts

Thursday, 7 June 2012

Make a ajax call using serve resource method in liferay

In liferay the ajax call has been done using the serve resource.

Example to add a Data on button call with the help of the ajax in liferay.

In the jsp

Created a  resource url and a form.
<portlet:resourceURL var="addToDo" id="addToDo"></portlet:resourceURL>
<form>
<input type="text" name="toDo" id="toDo">
<button name="Add" type="button" onclick="addToDo('<%=addToDo%>')">Add</button>
<div id="toDoList">


</div>
</form>

In the above code when click on the add button we have called  a java script method "addToDo" with the resource url as the parameter.

Js Code :
<script type="text/javascript">
function addToDo(addToDo){
    var todo =document.getElementById('toDo').value;
    $.ajax({
        url :addToDo,            
          data: {"todo":todo,"CMD":"addToDo"},
          type: "GET",
          dataType: "text",
        success: function(data) {              
              $("#toDoList").html(data);
        }
    });
}
 </script>
when click on the add button it calls the js function  addToDo in which we have passes resource url as the parameter.Fetch the value put into the text box .

In the controller.
By default it is going to call serve resource mthod of the controller.

public void serveResource(ResourceRequest request, ResourceResponse response){
        if(request.getParameter("CMD").equals("addToDo")){
            user_todo userToDo = new user_todoImpl();
            userToDo.setUserId(userId);
            try {
                userToDo.setTodoId(CounterLocalServiceUtil.increment());
                userToDo.setToDoName(request.getParameter("todo"));
                user_todoLocalServiceUtil.adduser_todo(userToDo);
                       
            }
            catch (SystemException e) {
                e.printStackTrace();
            }
   
        }
    }

It's going to add the todo list into the custom table made for making the todo entries.