• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Strut-Ajax - display states when Country selected

 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have a JSP page that has a Country drop-down list and a State drop-down list. I want to be able to retrieve a list of States when a Country is selected. I used Struts and JSP in our web applications. I was told that Ajax will be able to handle this more elegantly. I've never I'm new to Ajax.

So, I'm wondering how I can incorporate Struts and Ajax in my web application.

Here's my JSP code:

<html>
<script language='javascript'>

function setState(selectedState)
{
document.forms['SearchResultForm'].submit();
}

function setCountry(selectedCountry)
{
document.forms['SearchResultForm'].submit();
}

</script>

<body>
<html:form action="/submitSearch" >
<table align="right" width="400" border="0">
<tr align="right">
<td valign="top">
<select name="selectedCountry" onchange="return setCountry(this.options[this.selectedIndex].value);">
<option value='0'>--Select a Country--
<logic:iterate id="country" name="countryList">
<option value='<bean:write name="country" property="countryCode"/>' > <bean:write name="country" property="countryName"/>
</logic:iterate>
</td>
<td valign="top">State:<select name="selectedState" onchange="return setState(this.options[this.selectedIndex].value);">
<option value='0'>
<logic:iterate id="state" name="stateList">
<option value='<bean:write name="state" property="stateId"/>' > <bean:write name="state" property="stateName"/>
</logic:iterate>
</select>
</td>
</tr>
</table>


...

</html>

Pls...HeLp!!!
 
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is generally referred to as a "dependent select" or "dependent dropdown". If you google "ajax dependent select" you'll see a lot of different methods for doing this. You might find the link below helpful, as it is specific to Struts:

http://www.artima.com/forums/flat.jsp?forum=121&thread=140644

Also, if you use the search function on this forum for the above terms, you will find other posts dealing with that issue.
 
Nina Anderson
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the site.

I followed the struts-AJax's examples, and my jsp page is able to send the request to my Struts Action process. However, the data the gets forwarded back to the JSP page is making it into the responseText. I'm writing the data into the PrintWriter object but that data is not making it back.

Can someone Please let me know what I'm doing wrong. This is my first time using AJAX and I'm pulled all my hair trying to debug this

Here's my code:

/// JSP ////

<script language='javascript'>

var req;
/*
* Get the second options by calling a Struts action
*/
function getStates(selectedCountry, countrySelectBox)
{
document.forms['SearchResultForm'].submit();
url="http://localhost:9080/PBWebApp/displayHomePage.do?selectedCountry="+selectedCountry;

//Do the Ajax call
if (window.XMLHttpRequest){ // Non-IE browsers
req = new XMLHttpRequest();
//A call-back function is define so the browser knows which function to call after the server gives a reponse back
req.onreadystatechange = populateSecondBox;

req.open("GET", url, true); //was get
req.send(null);
}

//Do the Ajax call
if (window.XMLHttpRequest){ // Non-IE browsers
req = new XMLHttpRequest();
//A call-back function is define so the browser knows which function to call after the server gives a reponse back
req.onreadystatechange = populateSecondBox;

req.open("GET", url, true); //was get
req.send(null);
}

else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = populateSecondBox;
req.open("GET", url, true);
req.send(null);
}
}
}

//Callback function
function populateSecondBox(){
document.forms['SearchResultForm'].selectedState.options.length = 0;

if (req.readyState == 4) { // Complete

alert("xml doc1");

if (req.status == 200) { // OK response


alert(req.responseText);

textToSplit = document.createTextNode(req.responseText);



if(textToSplit == '803'){
alert("No select option available on the server")
}

//Split the document
returnElements=textToSplit.split("||")

//Process each of the elements
for ( var i=0; i<returnElements.length; i++ ){

valueLabelPair = returnElements[i].split(";")
alert("label - " + valueLabelPair[0]);
document.forms['SearchResultForm'].selectedState.options.length = returnElements.length;
document.forms['SearchResultForm'].selectedState.options[i] = new Option(valueLabelPair[0], valueLabelPair[1]);
}
}
}

}

</script>

<body>

<bean efine id="critDto" name="SearchResultForm" property="criteriaDto" type="com.PBCoreApp.datatransfer.SearchCriteriaDTO" />
<table style="background-repeat:no-repeat;" background="../images/bgMain.jpg" align="center" width="960" height="532" cellpadding="0" cellspacing="0" border="0">
<tr>
<td colspan="2">

<html:form action="/displayHomePage" >
<table align="right" width="400" border="0">
<tr align="right">
<td valign="top">Country
<html:select property="selectedCountry" name="SearchResultForm" onchange="return getStates(this.options[this.selectedIndex].value, this);">
<html ptions collection="countryList" name="SearchResultForm" property="value" labelProperty="label" />
</html:select>

</td>
<td valign="top">State:
<html:select property="selectedState" name="SearchResultForm" >
<html ptions collection="stateList" property="value" labelProperty="label" />
</html:select>
</td>



///// STRUTS Action ////

public class MainSearchDisplayAction extends Action {
/*
* Generated Methods
*/

ServletContext context = null;

public void setServlet(ActionServlet servlet)
{
context = servlet.getServletContext();
}

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping_, ActionForm form_,
HttpServletRequest request_, HttpServletResponse response_) {

DynaValidatorForm form = (DynaValidatorForm) form_;

if( request_.getParameter("selectedCountry") != null && request_.getParameter("selectedCountry").length() > 0)
{
PopulateAjaxLabelValue populateAjaxValues = new PopulateAjaxLabelValue();
SearchBS searchBS = new SearchBS();
String selectedCountry = null;

try {

response_.setContentType("text/xml");
PrintWriter out = response_.getWriter();

List states = searchBS.getStatesByCountry( new Integer(selectedCountry) );
//Make a String representation in format label;value||label;value
String outLine = populateAjaxValues.makeOutputString(states);
System.out.println("Response String - " + outLine);
out.print(outLine);

} catch (Exception e) {

System.out.println("Exception occurred - " + e);
}

}

return mapping_.findForward("mainSearch");
}


///// STRUTS CONFIG /////

<action path="/displayHomePage" scope="session" type="com.poshWebApp.action.MainSearchDisplayAction" name="SearchResultForm" validate="false" >
<forward name="mainSearch" path="/web/search/home.jsp"/>
</action>


Thanks in Advance
 
Nina Anderson
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
does anyone know Ajax...that can assist me? I'm clueless here.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic