In this example iam retrieving the data from mysql database using ajax+json using liferay
package
com.phone;
import
com.phone.slayer.service.*;
import
java.io.IOException;
import
java.io.PrintWriter;
import
java.util.List;
import
com.phone.slayer.service.PhoneLocalServiceUtil;
import
javax.portlet.ActionRequest;
import
javax.portlet.ActionResponse;
import
javax.portlet.PortletException;
import
javax.portlet.ResourceRequest;
import
javax.portlet.ResourceResponse;
import
com.liferay.counter.service.CounterLocalServiceUtil;
import
com.liferay.portal.PortalException;
import
com.liferay.portal.SystemException;
import
com.liferay.portal.kernel.json.JSONFactoryUtil;
import
com.liferay.portal.kernel.json.JSONObject;
import
com.liferay.portal.kernel.util.ParamUtil;
import
com.liferay.util.bridges.mvc.MVCPortlet;
import
com.phone.slayer.model.Phone;
public class
PhonePortlet extends MVCPortlet {
public void
serveResource(
ResourceRequest
resourceRequest, ResourceResponse resourceResponse)
throws IOException,
PortletException {
try{
System.out.println("JSON
Ajax Call....");
String
pid2=ParamUtil.getString(resourceRequest, "pid");
long
pid=ParamUtil.getLong(resourceRequest, "pid");
System.out.println("Name -----"+pid+""+pid2);
PrintWriter writer =
resourceResponse.getWriter();
Phone names=
PhoneLocalServiceUtil.getPhone(pid);
System.out.println("......"+names);
JSONObject objJsonObject =
JSONFactoryUtil.createJSONObject();
objJsonObject.put("pid",names.getPid());
objJsonObject.put("pname",names.getPname());
objJsonObject.put("ptype",names.getPtype());
writer.print(objJsonObject);
}
catch (Exception e) {
// TODO: handle
exception
System.out.println("---"+e);
}
}
}
Display.jsp
<%@ taglib
uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib
uri="http://liferay.com/tld/aui" prefix="aui" %>
<portlet:defineObjects />
This is the <b>AjaxApp</b> portlet in View
mode.
<script type="text/javascript"
src="/html/js/jquery/jquery.js"></script>
<aui:form>
<aui:input name="pid"
label="pid" id="pid"></aui:input>
<aui:button name="getData"
value="Get Details" id="getData"></aui:button>
</aui:form>
<div id="a1"></div>
<div id="a2"></div>
<div id="a3"></div>
<portlet:resourceURL var="resourceURL"></portlet:resourceURL>
<script type="text/javascript">
$("#<portlet:namespace/>getData").click(function() {
var nameVal =
jQuery("#<portlet:namespace/>pid").val();
alert('hi'+nameVal);
jQuery.ajax({
url :'<%=resourceURL%>',
data: {pid:nameVal},
type: "POST",
dataType:
"json",
success: function(data) {
$("#a").html(data);
document.getElementById("a1").innerHTML="<font
color=green>PID:
</font>"+data["pid"];
document.getElementById("a2").innerHTML="<font
color=green>Pname:
</font>"+data["pname"];
document.getElementById("a3").innerHTML="<font
color=green>Ptype:
</font> "+data["ptype"];
}
});
});
</script>