DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

rupali has posted 1 posts at DZone. View Full User Profile

Dependant Dropdowns Using Ajax

03.20.2007
| 17482 views |
  • submit to reddit
        This code demonstrates using ajax for dependant combos.The sample application 
below has 2 combo boxes 1.country 2.city.
OnChange event on the country should populate the corresponding cities in the 
city dropdown.

--------------------------------------------------------------------------------
ajaxscripting.js
--------------------------------------------------------------------------------

<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

function doRequestUsingGETCountry(url) {
   
    createXMLHttpRequest();
    queryString =   url ;
    queryString = queryString + "&selcountry="+document.forms[0].country.options[document.forms[0].country.selectedIndex].value;
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", queryString, true);
    xmlHttp.send(null);
}

function handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
          parseResults();
        }
    }
}
function parseResults() {
            var responseText = document.createTextNode(xmlHttp.responseText);
            var returnElements=xmlHttp.responseText.split("||");
          //Process each of the elements 	
          for ( var i=0; i<returnElements.length; i++ ){
             
             if(returnElements[i]!="")
            {
             valueLabelPair = returnElements[i].split(";")
             document.getElementById('state').options.length= returnElements.length;     
             document.getElementById('state').options[i] = new Option(valueLabelPair[0], valueLabelPair[1]);
            } 
        }
}
function inc(filename)
{
var body = document.getElementsByTagName('body').item(0);
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
body.appendChild(script)
}

--------------------------------------------------------------------------------
dependantComboExample.jsp
--------------------------------------------------------------------------------
<%@page import="ajaxsample.SampleForm,java.util.*"%>
<%@include file="taglibs.jsp"%>
<%@include file="ajaxscripting.js"%>

<head>
</head>

<body onLoad="doRequestUsingGETCountry('/struts-ajax/DependantComboExample.do?');">

<html:form action="DependantComboExample.do" >

  <h1></h1>
  <table>
    <tbody>
        <tr>
            <td>Country</td>
              <td>
                <html:select property="country" name="inputForm" onchange="doRequestUsingGETCountry('/struts-ajax/DependantComboExample.do?');">
                    <html:options collection="countries" property="value" labelProperty="label"/>
                </html:select>
               </td>
               <td>
               <html:select property="state" name="inputForm" >
                    <html:options collection="states" property="value" labelProperty="label" />
                </html:select>                  
               </td>
        </tr>
    </tbody>
  </table>
  
</html:form>
</body>
</script>

------------------------------------------------------------------
GetAndPostExample
------------------------------------------------------------------


package ajaxsample;

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
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 java.util.ArrayList;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.util.LabelValueBean;

public class GetAndPostExample extends Action {
    
    ServletContext context = null;
    
    public void setServlet(ActionServlet servlet)
    {
        context =  servlet.getServletContext();
    }
   public ActionForward execute(ActionMapping mapping, ActionForm inForm, 
           HttpServletRequest request, HttpServletResponse response) throws Exception {
           response.setContentType("text/xml");

          String optionSelected = request.getParameter("selcountry");        
         //Build the response text
         
         SampleForm sform = (SampleForm)inForm;
         ArrayList countries = (ArrayList)context.getAttribute("countries");
         ArrayList states = (ArrayList)context.getAttribute("states");
         ArrayList newStates = new ArrayList();
         String responseText = "";
         //sending response text in the format label:value||label;value
         for(int i=0;i<states.size();i++)
         {
            LabelValueBean temp = (LabelValueBean)states.get(i);
            if(temp.getValue().startsWith(optionSelected))
            {
                    newStates.add(temp); 
                    responseText = temp.getLabel()+";"+temp.getValue()+"||"+responseText; 
            }
         }
         if(responseText.endsWith("||"))   //chop off the ending ||
         {
             responseText = responseText.substring(0, responseText.lastIndexOf("||"));
         }
         PrintWriter out = response.getWriter();
         out.println(responseText);
        //Close the writer
        out.close();
        return(mapping.findForward("content1"));
   }
  }
------------------------------------------------------------------
CacheServlet.java
------------------------------------------------------------------

package ajaxsample;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.IOException;
import org.apache.struts.util.LabelValueBean;
import java.util.*;
/**
 *
 * @author rupali_l
 */
public class CacheServlet extends HttpServlet {
    
    
    /** Creates a new instance of CacheServlet */
    public void init() throws ServletException {
   
      
        System.out.println("In do get of CacheServlet");
        ArrayList countries = new ArrayList(); 
        countries.add(new  LabelValueBean("India", "1" ));
        countries.add(new  LabelValueBean("U.S","2"));
        countries.add(new  LabelValueBean( "Australia","3"));
        
        ArrayList states = new ArrayList(); 
        states.add(new  LabelValueBean("Maharashtra","11"));
        states.add(new  LabelValueBean( "Delhi","12"));
        states.add(new  LabelValueBean("Goa","13"));
        states.add(new  LabelValueBean( "Newjersey","21"));
        states.add(new  LabelValueBean("NewYork","22"));
        states.add(new  LabelValueBean( "California","23"));
        states.add(new  LabelValueBean("Sydney","31"));
        getServletContext().setAttribute("countries", countries);
        getServletContext().setAttribute("states", states);
        
       
    }
        
    
    public void doGet(HttpServletRequest request ,HttpServletResponse response) throws ServletException,
    IOException
    {
        // request.getRequestDispatcher
    }       
            
    
}
------------------------------------------------------------------
web.xml
------------------------------------------------------------------


<web-app>
  <display-name>Struts Blank Application</display-name>
  
  <!-- Standard Action Servlet Configuration (with debugging) -->
  <servlet>
    <servlet-name>CacheServlet</servlet-name>
    <servlet-class>ajaxsample.CacheServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>

  
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>


  <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>


  <!-- Struts Tag Library Descriptors -->
  <taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>

</web-app>

struts-config.xml


<!-- ================================================ 
<struts-config>
<!-- ================================================

    <form-beans>
    
	<!-- <form-bean name="sampleForm" type="ajaxsample.SampleForm"/>
    -->
    
    <!-- sample form bean descriptor for an ActionForm-->
        <form-bean
            name="inputForm"
            type="ajaxsample.SampleForm"/>
 </form-bean>
    
    </form-beans>
 <action-mappings>
<action path="/DependantComboExample" type="ajaxsample.GetAndPostExample" 
    	name="inputForm" scope="request" validate="false" >
    	
    	<!-- Partial Ajax Content-->
    <forward name="content1" path="/dependantComboExample.jsp" />

</action-mappings>

</struts-config>




    

Comments

Snippets Manager replied on Sun, 2009/01/04 - 3:07am

Where is the Form... This code wouldn't work without the form class. Please post the SampleForm.java with the necessary collection fields to be populated.

Snippets Manager replied on Fri, 2008/08/29 - 1:36am

i had copied ur code and put in my project but it is not working.Where the .js file had to put ,how the first page started with the country data in it how the action are going.Data from the data base can be given to the database to the dropdown list pls put the correct code with full description pls help me im a new in struts with ajax pls send the corrected code to ssalish@gmail.com i'm using struts 1.2.thank you