Thursday, October 15, 2009

GenericPortlet & Ajax

Anyone familiar with form submission knows that the processAction takes care of the processing as far as the backend goes but in case you're wondering how to process an Ajax call, look no further.

In your JSP, you must use the ResourceURL ()

ResourceURL resourceURL = renderResponse.createResourceURL();

For this quick example, I use JavaScript to handle the call:

function delFav(thisFav) {
if(confirm("This will delete your favourite. Are you sure you want to continue?")) {
$("div#showaddfav").html(" Deleting your favourite. Please wait.");
$.post("<%=resourceURL%>", { delFav: thisFav, usersId: "<%=themeDisplay.getUserId()%>" },

if(checkType("del-saved", data) != -1) { $("#showaddfav").html("<span class="portlet-msg-success">Your favourite was deleted. Congrats!</span>"); }
if(checkType("error", data) != -1) { $("#showaddfav").html("<span class="portlet-msg-error">An unknown error has occured. Please notify the Administrator.</span>"); }
} else { return; }


function checkType(expr, thisUrl) {

And your portlet should use the serveResource for processing:

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

public void serveResource(ResourceRequest req, ResourceResponse resp)
throws PortletException, IOException {
PrintWriter writer = resp.getWriter();

// User want to delete
String delFav = ParamUtil.getString(req, "delFav");

try {

writer.print("<div id="response-wrap">del-saved</div>");

} catch (PortalException e) {
writer.print(" <div id="response-wrap">error</div>");
} catch (SystemException e) {
writer.print(" <div id="response-wrap">error</div>");

This of course is just example code but if you want to pass a tidbit of info back to your jsp you have to use the print (and don't forget to close the writer).

No comments:

Post a Comment