Thursday, April 30, 2015

Ajax and Struts 1 using jQuery Ajax with URL parameters

Here is an example of an ajax implementation using jQuery ajax with URL parameters and Struts 1.3 framework with Java.

 Here's what you will need in your project:

Files under Web App Libraries:
jackson-annotations-2.4.0.jar
jackson-core--2.4.2.jar
jackson-databind-2.4.2.jar

File under \WebContent\js:
jquery-1.11.1.min.js


In struts-config.xml:
     <action path="/updateParentInvoice"
       type="com.mycompany.action.UpdateParentInvoiceAjaxAction"
       scope="request"   
       input="/jsp/error.jsp"
       validate="false">      
     </action> 

In your javascript:
function updateParentInvoice(remitItemCode, invoiceNo, selectTagElement) {
 var parentInvoiceNo = selectTagElement.options[selectTagElement.selectedIndex].value;
 
    $.ajax({
        type: "GET",
        url: "/{myAppContext}/updateParentInvoice.do",
        //Data to be sent to the server. It is converted to a query string, if not already a string. 
        //For GET-requests, it's appended to the url. For POST-requests, it is sent as Form properties. 
        //Object must be Key/Value pairs
        data: {"remitItemCode":remitItemCode, "invoiceNo":invoiceNo, "parentInvoiceNo":parentInvoiceNo}, 
        //use this default content type when sending data to the server, which is fine for most cases.
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        //dataType is type of data that you're expecting back from the server
        dataType: "text",        
        success: function(response){
         alert("response from ajax call \n" + response);
        },
        error: function(e){
            //alert('Error: ' + e);
        }
    }); 
}


In your jsp:
<select id='parentInvSelect-<c:out value="${invoiceNo}"/>' class="invSelect" name="<c:out value="${customerName}" />" onchange="updateParentInvoice('<c:out value="${remitItemCode}" />', '<c:out value="${invoiceNo}" />', this);">
 <option value="">Select One</option>
 <c:forEach var="parentInvoiceNo" items="${invoiceVB.parentInvoiceList}">            
  <option value='<c:out value="${parentInvoiceNo}" />'><c:out value="${parentInvoiceNo}" /></option>  
 </c:forEach>
</select>


In action class (UpdateParentInvoiceAjaxAction.java):
package com.mycompany.action.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.util.LogHelper;


/*
 *  Author; Eric Soriano
 *  
 *  
 */
public class UpdateParentInvoiceAjaxAction extends Action {
 
 private static final LogHelper LOG = new LogHelper(IncentiveRequestUpdateParentInvoiceAjaxAction.class);
 
 public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
  LOG.debug("START");
  
  String remittanceItemCode = (String)request.getParameter("remitItemCode");
  String invoiceNo = (String)request.getParameter("invoiceNo");
  String parentInvoiceNo = (String)request.getParameter("parentInvoiceNo");
  LOG.debug("Ajax request parameters received: remittanceItemCode = " + remittanceItemCode + " invoiceNo = " + invoiceNo + " parentInvoiceNo = " + parentInvoiceNo );
  
  //add code here to update parentInvoiceNo to the db
  
  response.setContentType("text/text;charset=utf-8");
  response.setHeader("cache-control", "no-cache");
  PrintWriter out = response.getWriter();
  out.println("remittanceItemCode = " + remittanceItemCode + " invoiceNo = " + invoiceNo + " parentInvoiceNo = " + parentInvoiceNo);
  out.flush();
  
  //since this is an ajax call, just return null so that struts does not take any further action
  return null;
 }

}



That's it. Very simple.