Ajax code to load combo values dynamically based on the selection of another combo.Example Code in Struts 1.2

The following code illustrates how to populate combo / dropdown list dynamically based on the selection of item from another combo without refreshing the page. For example a page has two combos/dropdown lists (named state , district), when we select a state from the state combo, the district combo will be populated with all the districts of the corresponding state dynamically without refreshing the page. This can be done using ajax. Using Ajax, web applications can send data to server and retrieve data from server asynchronously without refreshing the page. This process is done in the background without interfering the display and behavior of the existing page. Data are usually retrieved using the XMLHttpRequest object / ActiveXObject(“Microsoft.XMLHTTP”)

Ajax code to display combos dynamically based on the selection of another combo is given below. The following code is based on the struts 1.2.

JSP Code :

For creating combos and loading district values based on the selection of  another combo.


<html:form name="listForm" 	type="javaonline.ListForm" method="post" scope="request"	action="/listTest.do" target="_blank" onsubmit="return submitForm()">
					<html:hidden property="method" />
<div id="fullDiv" style="width:100%" >

<div >

    <div><label> State : </label>
    	<html:select name="listForm" property="stateId" styleId="stateId" styleClass="selBox" onchange="javascript:getDistList()" size="1">
   			<html:optionsCollection name="listForm" property="stateList" label="label" value="value"  />
		</html:select> </div>

  	<div>    Districts :
  		<html:select name="listForm" property="districtId" styleId="districtId" styleClass="selBox" size="1">
		<option value="0">Select</option>
			<html:optionsCollection name="listForm" property="distList" label="label" value="value" />
		</html:select>
	</div>		

</div>		

</div>

<script type="text/javascript">

var httpRequest;

    function getDistList()
     {
      var stId=document.listForm.stateId.value;

//AJAX Request
     var url = "servlet/javaonline.GetDistricts?method=GetDistricts&stateId="+stId;

      if (window.ActiveXObject)
        {
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else if (window.XMLHttpRequest)
        {
            httpRequest = new XMLHttpRequest();
        } 

        httpRequest.open("GET", url, true);
        httpRequest.onreadystatechange = function() {processRequest(); } ;
        httpRequest.send(null);  

  }

     function processRequest()
    {
        if (httpRequest.readyState == 4)
        {
            if(httpRequest.status == 200)
            {
             var distListXML = httpRequest.responseXML.getElementsByTagName("DistNames")[0];
             updateDistricts(distListXML);
            }
            else
            {
                alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
            }
        }
    } 

    function updateDistricts(distListXML)
    {
		var loop=0;
                var len = window.document.listForm.districtId.options.length;
		  while(len>0) {
		   len = len -1;
		   window.document.listForm.districtId.options[len] = null;
		  }//end while  

            window.document.listForm.districtId.options[0] = new Option("Select","0");

    			for (loop = 0; loop < distListXML.childNodes.length; loop++) {
			   distid = distListXML.getElementsByTagName('DistId')[loop];
			   distName = distListXML.getElementsByTagName('DistName')[loop];
			  eval(document.getElementById("districtId")).options[loop+len+1] = new Option(distName.childNodes[0].nodeValue,distid.childNodes[0].nodeValue);
				}

       return;
 }

</script>

</html:form>

Form, Action and DAO code for loading State values

public class ListAction extends DispatchAction{

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

				ActionForward forward = new ActionForward();
				String strTarget = "";
				try
				{
				System.out.println("Load State");
					ArrayList statelist = new ArrayList();
					ArrayList distlist = new ArrayList();

					ListForm listForm = (ListForm) form;
					LoginDAO logindao = new LoginDAO();
					statelist  = logindao.loadStates();
					listForm.setStateList(statelist);
					listForm.setDistList(distlist);

					strTarget = "loadState";
				}
				catch (Exception ex)
				{
					System.out.println(" Excp:loadState:" + ex.toString());
					strTarget = "timeout";
				}

				forward = mapping.findForward(strTarget);
				return (forward);

			}

       }

DAO code to load state lists

public class ListDAO {
	public ArrayList loadStates() {

		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet res = null;
		ArrayList stateList = new ArrayList();

		String sqlstr = "";
					sqlstr = "select stateid ,statename from state order by statename";

		try {

			con = ConnectionFactory.getConnection();

			pstmt = con.prepareStatement(sqlstr);
			res = pstmt.executeQuery();

			while (res.next())
			{
			stateList.add(new LabelValueBean(res.getString("STATENAME"),res.getString("STATEID")));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (!(res == null))
					res.close();
				if (!(pstmt == null))
					pstmt.close();
			} catch (SQLException e) {

			}
		}
		return stateList;
	}

	public ArrayList loadDistList(String stateId)   {
		  String strQuery;
		  boolean insert = false;
		  Connection conn = null;
		  ResultSet rs = null;
		  PreparedStatement pstmt = null;
		  ArrayList distList = new ArrayList();

		  try {
		   conn = ConnectionFactory.getConnection();
		   strQuery = " select  districtid, name from districts where stateid=?";
		   pstmt = conn.prepareStatement(strQuery);
		   pstmt.setString(1, stateId);
		   rs = pstmt.executeQuery();
		   while (rs.next()) {
		    distList.add(new LabelValueBean(rs.getString("name"),rs.getString("districtid")));

		   }

		  } catch (SQLException sqlExp) {
			  System.out.println("error1 " + sqlExp.getMessage());
			} catch (Exception e) {
				System.out.println("error " + e.getMessage());
				e.printStackTrace();

		  } finally {
		   try {
		    if (pstmt != null) { pstmt.close();pstmt = null; }
		    if (rs != null) { rs.close();rs = null;}
		    if (conn != null) {conn.close();conn = null; }
		   } catch (SQLException expSQL) {
		   }
		  }
		  return distList;
		 }

  }

Form Code : 

package javaonline;

import java.util.ArrayList;

import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;

public class ListForm extends ActionForm{

	private String method = null;
	private String stateId = null;
	private String districtId = null;
	private ArrayList stateList = null;
	private ArrayList distList = null;

	public String getDistrictId() {
		return districtId;
	}

	public void setDistrictId(String districtId) {
		this.districtId = districtId;
	}

	public ArrayList getDistList() {
		return distList;
	}

	public void setDistList(ArrayList distList) {
		this.distList = distList;
	}

	public String getStateId() {
		return stateId;
	}

	public void setStateId(String stateId) {
		this.stateId = stateId;
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public ArrayList getStateList() {
		return stateList;
	}

	public void setStateList(ArrayList stateList) {
		this.stateList = stateList;
	}

}

Servlet code to load districts XML when AJAX request is called from JSP


package javaonline;

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

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

import java.sql.Connection;
import java.util.*;
import java.io.*;
import org.apache.struts.util.LabelValueBean;

import confonet.login.LoginDAO;

public class GetDistricts extends HttpServlet  {

	protected void doGet(HttpServletRequest requestObj, HttpServletResponse responseObj)
				   throws IOException
	{
		responseObj.setContentType("text/xml;charset=UTF-8");
		responseObj.setHeader("Cache-Control", "no-cache");
		//get the PrintWriter object to write the html page
		PrintWriter writer = responseObj.getWriter();
		String statecode= (String)requestObj.getParameter("stateId");
		System.out.println("state id" + statecode);
			ArrayList districts=new ArrayList();
			Connection con=null;
			//ArrayList districtList=new ArrayList();
			try
			{
				ListDAO listDAO = new ListDAO();
				districts = listDAO.loadDistList(statecode);
			}
			catch(Exception e)
			{

				System.out.println("GetDistricts::doPost:Excp:"+e.toString());
			}

			System.out.println("size arrya" + districts.size());

		   Iterator it =districts.iterator();

				writer.println("<DistNames>");
				while(it.hasNext())
					{

					LabelValueBean l=(LabelValueBean)it.next();

					writer.println("<DETAIL>");

					writer.println("<DistId>"+l.getValue()+"</DistId>");
					writer.println("<DistName><![CDATA["+l.getLabel() +"]]></DistName>");
					writer.println("</DETAIL>");
					}
			//	writer.println("<Profile><![CDATA[" + "Jegan1" + "]]></Profile>");
				//close the write
				writer.println("</DistNames>");

				writer.close();	

	}     

	protected void doPost(
		HttpServletRequest requestObj,
		HttpServletResponse responseObj)
		throws ServletException, IOException {
		}

}

struts-config.xml


      <form-beans>

       <form-bean name="listForm"  type="javaonline.ListForm"/>

       </form-beans>

 <action name="listForm" path="/listTest" scope="request" type="javaonline.ListAction" validate="true" parameter="method">
     <forward name="loadState" path="JavaOnline/AjaxComboTest.jsp"></forward>
 </action>

You may also like

Leave a Reply

Be the First to Comment!