wood burning stoves 2.0*
The moose likes HTML, CSS and JavaScript and the fly likes populate <html:options> with AJAX response Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "populate <html:options> with AJAX response" Watch "populate <html:options> with AJAX response" New topic
Author

populate <html:options> with AJAX response

Deeps Mistry
Ranch Hand

Joined: Jan 31, 2009
Posts: 189
Hi,

I have two drop down list. On selection of a value in the first drop down list, the second drop down list should automatically get populated.

For this i am using AJAX + struts 1.1

I am calling the ajax function on change of the 1st drop down list. In the ajax function am making a call to my action class, which does the fetching from the database and sends the response back to the jsp.

I am getting the response in my jsp but I am not able to populate it in my <htmlptions> tag.

My jsp page:


AJAX function:


Action class:

How do i populate my AJAX response in <htmlptions> tag?

Please help me out.

Thanks

Aditya Keyal
Ranch Hand

Joined: Dec 01, 2008
Posts: 71
the response that is being streamed back should be in the form of


<option>val1</option>
<option>val2</option>
<option>val3</option>

so change the code in the action accordingly..


- Aditya Webservices Blog
Aditya Keyal
Ranch Hand

Joined: Dec 01, 2008
Posts: 71
currently the code that you have written returns the objectId of an array. Thats meaningless to the <select>. Your code must change a lot.

Instead of the array use a string buffer. and change the code as shown:


Deeps Mistry
Ranch Hand

Joined: Jan 31, 2009
Posts: 189
Aditya Keyal wrote:currently the code that you have written returns the objectId of an array. Thats meaningless to the <select>. Your code must change a lot.

Instead of the array use a string buffer. and change the code as shown:




Hey..thanks for your prompt reply.
After having done this..how do i populate it in my select tag?

<edit>I tried the following :
document.getElementById("selectID").value = req.responseText;

also,
document.getElementById("selectID").innerHTML= req.responseText;

But no luck. The drop down is not getting populated.


Thanks
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61316
    
  66

What made you think value would be appropriate? That holds the value of the control.

Employ DOM manipulation, innerHTML, or the API for the Select element.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Deeps Mistry
Ranch Hand

Joined: Jan 31, 2009
Posts: 189
Bear Bibeault wrote:What made you think value would be appropriate? That holds the value of the control.

Employ DOM manipulation, innerHTML, or the API for the Select element.
ey

Hey,

I tried using innerHTML, but didnt show anything in the drop down.

Have no idea about DOM manipulation and API. Can you please guide me as to what should i do?

Thanks.


Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61316
    
  66

Select element API: http://java.sun.com/j2se/1.4.2/docs/guide/plugin/dom/org/w3c/dom/html/HTMLSelectElement.html

Be aware that IE doesn't follow this standard exactly.

Or, make it easy on yourself and employ jQuery which makes this sort of thing easier. If you download the code for my jQuery book from its web page you'll find examples of creating dynamic dropdowns in the Chapter 8 sample code

You can see the sample code in action here.
Deeps Mistry
Ranch Hand

Joined: Jan 31, 2009
Posts: 189
Bear Bibeault wrote:Select element API: http://java.sun.com/j2se/1.4.2/docs/guide/plugin/dom/org/w3c/dom/html/HTMLSelectElement.html

Be aware that IE doesn't follow this standard exactly.

Or, make it easy on yourself and employ jQuery which makes this sort of thing easier. If you download the code for my jQuery book from its web page you'll find examples of creating dynamic dropdowns in the Chapter 8 sample code

You can see the sample code in action here.


Hi,
Is there no way out using javascript + AJAX? Cant we create an option element in javascript?

Please help me out.
Thanks
Arpit Purohit
Greenhorn

Joined: Jan 09, 2007
Posts: 21
Try following Javascript code snippet (tested on IE6 and Firefox 3.0.8)


Regards,
Arpit Purohit
Deeps Mistry
Ranch Hand

Joined: Jan 31, 2009
Posts: 189
Arpit Purohit wrote:Try following Javascript code snippet (tested on IE6 and Firefox 3.0.8)


Hey
I tried what you suggested, but now the javascript function is not being called.
I think some problem with the syntax, but cant figure it out. Also, i am using struts tag. So is it possible to create a <htmlptions> tag in javascript?

Thanks for your help.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61316
    
  66

Deeps Mistry wrote:Also, i am using struts tag. So is it possible to create a <htmlptions> tag in javascript?

That makes no sense. Struts tags, just as any other JSP mechanism, operates on the server to generate HTML to send to the browser. Once it leaves the server, it's just plain old HTML.

And yes, you can create options with raw JavaScript. The DOM API I pointed you to, and that Arit gave you sample code for, is the way.

hem raj
Greenhorn

Joined: Apr 07, 2010
Posts: 11
Please refer this code .......

in js file

var req;
function ajaxFunction(value)
{
//Do the Ajax call
url = "<bean:message key="ohc.homeurl" bundle="alias"/>/action.do?method=fillCombo&deptId="+value;
// alert(url);
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("POST", url, true); //was get
alert('open')
} catch (e) {
alert("Problem Communicating with Server\n"+e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE

// alert("in I.E");
req = new ActiveXObject("Microsoft.XMLHTTP");
// alert(req);

if (req) {
// alert("in side req");
req.onreadystatechange = populateSecondBox;
req.open("POST", url, true);
req.send();
}
}
}
/* function processMessage() {
alert("function called");
alert("in process "+req.readyState);
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
alert('ready');
alert("Ajax response:"+req.responseText);

document.getElementById("secondBox").innerHTML = req.responseText;


} else {
alert("Problem with server response:\n " + req.responseText);
}

}
}*/
//Callback function
function populateSecondBox()
{
var returnElements;
var flag=0;
document.getElementById('hodBox').options.length = 0;
document.getElementById('secondaryBox').options.length = 0;
var cnt=0;
if (req.readyState == 4)
{ // Complete
if (req.status == 200)
{ // OK response
textToSplit = 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-1; i++ )
{
valueLabelPair = returnElements[i].split(";");
if (valueLabelPair[1]!='**' && valueLabelPair[0]!='**')
{
document.getElementById('hodBox').options[i] = new Option(valueLabelPair[1], valueLabelPair[0]);
cnt++;
}
else
break;
}
document.getElementById('secondaryBox').options.length = 0;
var j=0;
for ( var i=cnt+1; i<returnElements.length-1; i++,j++ )
{
valueLabelPair = returnElements[i].split(";");
document.getElementById('secondaryBox').options[j] = new Option(valueLabelPair[1], valueLabelPair[0]);
}
}
}
}


in jsp

<html:select property="deptCode" onchange="ajaxFunction(this.value)" styleId="deptBox">
<option value="" selected="selected" ><bean:message key="label.select"/></option>
<htmlptionsCollection name=""
property=""
value="deptCode"
label="deptName"/>

<html:select property="hodEcNo" onchange="setEcNo()" styleId="hodBox">
<htmlption value="nothing">--Select Department First -</htmlption>

<html:select property="secondaryEcNo" onchange="setEcNo()" styleId="secondaryBox">
<htmlption value="nothing">--Select Department First -</htmlption>


in Action File


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

ResultSet rSet = null;
String deptCode=request.getParameter("deptId");

System.out.println("deptCode : "+deptCode);
DataSource ds = (DataSource)getDataSource(request);
DataBase db = new DataBase();
String combo="select ec_no,initcap(e_name) from emp order by initcap(e_name)";
System.out.println("qry : "+combo);
if(db.connectDB(ds,request))
{
rSet = db.getData(combo);


String outputString="Null;--Select--||";
while(rSet.next())
{


outputString=outputString+rSet.getString(1);
outputString=outputString+";";
outputString=outputString+rSet.getString(2);
if (rSet.next())
{
outputString=outputString+"||";
rSet.previous();
}
else
break;
}
outputString=outputString+"||";
System.out.println("output String 1= " + outputString);
outputString=outputString+"**;**||";
outputString= outputString+"Null;--Select--||";
combo="select ec_no,initcap(e_name) from emp order by initcap(e_name)";
rSet = db.getData(combo);
while(rSet.next())
{
outputString=outputString+rSet.getString(1);
outputString=outputString+";";
outputString=outputString+rSet.getString(2);
if (rSet.next())
{
outputString=outputString+"||";
rSet.previous();
}
else
break;
}
outputString=outputString+"||";

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(outputString);

out.flush();
out.close();


}
return mapping.getInputForward();
}
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61316
    
  66

"vng sys", please check your private messages for an important administrative matter.

And, please read this: UseCodeTags.
 
wood burning stoves
 
subject: populate <html:options> with AJAX response