Quantcast
Viewing all articles
Browse latest Browse all 10

How to write simple response for Ajax request using JQuery and Struts

This simple example show the code how to create client code using JQuery`s ajax.
I assumed that you have already familiar with Struts Framework.
The rest of the code are omited for the sake of brevity.

I do used struts configuration as follow:

 <struts-config>
  <form-beans>
	  <!-- For Monthly Quarterly Reports -->
	  <form-bean name="monthlyQuarterlyReportForm" type="com.sim.aeg.report.monthlyQuarterlyReport.form.MonthlyQuarterlyReportForm">
	  <form-property name="institution" type="java.lang.String" initial="ALL"/>
	  <form-property name="department" type="java.lang.String" initial="-"/>
  </form-bean>
  <action-mappings>
	  <!--  For Monthly Quarterly Reports -->
	  <action name="monthlyQuarterlyReportForm" parameter="method"
	   path="/report/monthlyQuarterlyReportAction" scope="request" type="com.sim.aeg.report.monthlyQuarterlyReport.action.MonthlyQuarterlyReportAction">
	   <forward name="unspecified" path="report.monthlyQuarterlyReport"/>
	  </action>
  </action-mappings>
 </struts-config>

Client side code:

	var theForm = $("form[name=monthlyQuarterlyReportForm]");
	var params = theForm.serialize();
	var actionURL = theForm.attr("action"); 
	$.ajax({
		type:"POST",
		url:actionURL,
		data:params,
		success:function(data, textStatus, XMLHttpRequest){
			alert(data);//data will contain "This is the text response which will be sent to the client" text.
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			alert(textStatus);
		}
	});

I put the client side code in a click event of a button.

Server side code:

	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

			response.setContentType("text");
			response.getWriter().print("This is the text response which will be sent to the client");
			return null;
	}

That is all, I hope it helped.


Viewing all articles
Browse latest Browse all 10

Trending Articles