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.



8 comments:

  1. Superb..................

    ReplyDelete
  2. HI you have written nice blog but not provide database or service.xml detail for custom table.

    ReplyDelete
  3. You don't know how much you have saved me, Thank you

    ReplyDelete
  4. Great stuff man...i'm fixated.

    ReplyDelete
  5. data is not getting fetched in controller.. please help me..

    ReplyDelete
    Replies
    1. can u pls provide me your code.

      Delete
    2. code is same as yours.. and if I pass ths whole form instead of data.. it works..

      Delete