Avatar of GlobalDictator
GlobalDictator
 asked on

Populating a HTML DropDown from an Array returned by Javascript and Java

Hi,

I've got a drop down in the HTML that needs to be populated dynamically with a list of userIds from the database. Hence, I need to execute the JavaScript function calling the Java function to query the DB before the HTML page loads. As I need to execute the JS function before the page loads, I'm importing the javascript (Users.js) in the head section and calling my JS function (findActiveOrganisationsRequest('findActiveOrganisations')" on the atload() method in the Body tag of the HTML.

Q1. Whats the best way to get that JS function to run before form loads so I can populate the dropdown? Will the above do the trick? My HTML is:
   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 
    Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<title>Sample User Registration</title>		
		<script language="javascript" src="js/Users.js"> </script>
	</head>

    <body atload="findActiveUsersRequest(findActiveUsers)">
        <H2>User Registration</H2>                        
        <div id="userAccessForm" >
	 <form name="userAccessForm" id="userAccessForm">
	<div id="userAccessResults" style=" width : 364px; float:left;"></div><br>		<table width="100%" border="1px">
	<tr><td> 	<p>Organisation *<br>
	    <select name="UserID" id="UserID">					<option value="Choose your Organisation" selected>Choose Username</option>
		<option value="1">Dynamically populate User1</option>					<option value="2">Dynamically populate User2</option>					<option value="3">Dynamically populate user3</option>					</select>	</p><td>
	<input name="submit" type="submit" id="submit" value="Submit">				<input name="reset" type="reset" id="cancel" value="Cancel">
	</td></tr>
    <tr><td>
    <div id="UserResults" style=" width:353px; float:left;"></div></td></tr>
	</table>
	</form></body>
</html> 

Open in new window




Q2. Now, how do I populate the DropDown with the list returned back by the JS function. My javascript function is as follows:

   
function findActiveUsersRequest(findActiveUsers){
	var xmlhttp;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = function() {
		var returnText = xmlhttp.responseText;
		document.getElementById("UserResults").innerHTML=returnText;
	};
	
	var loadingHtml = "<img border=\"0\" src=\"images/busy.gif\" width=\"50\" /> Active Users Details...";
	document.getElementById("UserResults").innerHTML=loadingHtml;
	xmlhttp.open("GET","mets?action=users&userAction="+findActiveUsers);	
	xmlhttp.send();	
    }

Open in new window


As evident, the last 2 lines of the above JS function send a HTTP request which gets caught by the servlet, which then

a) checks for the parametes coming in the HTTP request,

b) Gets the results from the Database

c) Creates a StringBuffer array in response in th format as "UserID - UserName". But I'm not sure that this is the best way of doing it..Any help/suggestions will be most appreciated!!

d) Sends that response as follows:  sendResponse(response.getWriter(), stringBuffer)

The code for the Java Servlet is:
   
import java.io.PrintWriter;
    import java.util.List;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;

    public class RequestActionFactory {
	@SuppressWarnings("unchecked")
	public static Action getAction(HttpServletRequest request) {
		// Retrieve action parameters
		String action = request.getParameter("action");
		String userAction = request.getParameter("UserAction");
		

                  // Validate
		if (action != null) {
			// Event request
			if (action.equals("users")) {
				List<UserIdDTO> userDTOList = getActiveUsers(); //Gets the UserIds from the DB
				StringBuffer[] stringBuffer = new StringBuffer[userDTOList.size()];							
				for (UserIdDTO userDTO : userDTOList) {
					for(int i=0; i<userDTOList.size(); i++) {
						stringBuffer[i] = new StringBuffer();
						stringBuffer[i].append(responseValue(userDTO));
					}
				}			
				sendResponse(response.getWriter(), stringBuffer); 
			} 
		}		
		return null;		
	}
	
	private StringBuffer responseValue(UserIdDTO userDTO){
		StringBuffer strBuffer = new StringBuffer();
		strBuffer.append(userDTO.getId());
		strBuffer.append(" - ");
		strBuffer.append(userDTO.getuserName());		
		return strBuffer;
	}	
	
	public static void sendResponse(PrintWriter writer, StringBuffer[] stringBuffer) {
		if (stringBuffer != null) {			
				for(int i=0; i<stringBuffer.length; i++) {					
					if(null!=stringBuffer[i]) {
						writer.write(stringBuffer[i].toString());
				}	
			} 
		} else {
			// TODO write to log			
		}		
	}	
    }

Open in new window


Once the Java Servlet sends a response back, it gets caught in the JS functions mentioned above as:

   
xmlhttp.onreadystatechange = function() {
		var returnText = xmlhttp.responseText;
		document.getElementById("UserResults").innerHTML=returnText;
	};

Open in new window


So, I am successfully able to display the array in the UserResults DIV tag on my form as:

1 - john.Smith

2 - Adam.smith

3 - Peter.smith

But how can I use this array to populate my drop down in the form???

Any help will be most appreciated!!

Thanks
JavaScriptJava

Avatar of undefined
Last Comment
GlobalDictator

8/22/2022 - Mon
CEHJ

If you're not doing this server side (and you're not, although not sure why), this is a JavaScript question and shouldn't be in this TA
chaitu chaitu

  function selectAccount() {

  var myarray = ["1-john.Smith","2-Adam.smith","3-Peter.smith"];


    var result = "<select name='results'/>";

    for (var key in myarray) {
        result += "<option value="+myarray[key].split("-")[0]+">"+myarray[key].split("-")[1]+"</option>";
    }

		document.getElementById("results").innerHTML=result;

}
 </head>

 <body onload='selectAccount()'>
 <div id='results'></div>
  
 </body>

Open in new window

chaitu chaitu

var returnText = xmlhttp.responseText

if your returnText  is in this format ["1-john.Smith","2-Adam.smith","3-Peter.smith"];
you can iterate it like i shown you above and display it in drop down .
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
GlobalDictator

ASKER
@CEHJ,

As part of my 2nd question, I needed to find out whether StringBuffer created in the HTTP response within the Java Servlet was the right way or not. Hence in both Java and JavaScript tags.
GlobalDictator

ASKER
@chaituu,

Could you please elaborate a bit more and some sample code will be most beneficial.

Thanks
chaitu chaitu

construct the string in below format.

for (UserIdDTO userDTO : userDTOList) {
				for(int i=0; i<userDTOList.size(); i++) {
					stringBuffer[i] = new StringBuffer();
					stringBuffer[i].append("["+responseValue(userDTO)+"],");
				}
			}	
			
			stringBuffer.toString().substring(stringBuffer.length-1);

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
chaitu chaitu

put alert and see how your string is coming out.

xmlhttp.onreadystatechange = function() {
            var returnText = xmlhttp.responseText;
alert(returnText )
            document.getElementById("UserResults").innerHTML=returnText;
      };
GlobalDictator

ASKER
@chaituu,

OK, I'll do that but this will still only get me the array in the JS file. How do I then pass this over to my HTML so I can use the returnText  variable in HTML?
chaitu chaitu

xmlhttp.onreadystatechange = function() {

		var returnText = xmlhttp.responseText;

//first check here how the returnText is coming......

var result = "<select name='results'/>";

    for (var key in myarray) {
        result += "<option value="+myarray[key].split("-")[0]+">"+myarray[key].split("-")[1]+"</option>";
    }
		document.getElementById("UserResults").innerHTML=returnText;



	};

Open in new window

Your help has saved me hundreds of hours of internet surfing.
fblack61
chaitu chaitu

this returnText  in onreadystatechange  function  should be in this format then only it will work;
["1-john.Smith","2-Adam.smith","3-Peter.smith"];

Open in new window

GlobalDictator

ASKER
@chaituu,

Yes, thats the format that the result is received back. And I can see that we are building 'result' as the drop down by using the Select tag and then adding the options to it. But

1) where do we pass the 'result' drop down to the html form?

2) Regarding (var key in myarray), where is this array created? The results we get from the DB will probably be different each time they are retrieved.
GlobalDictator

ASKER
@chaituu,

Your changes brings the following back: [1 - John.smith],[2 - adam.smith],[3 - peter.smith]
Do we strictly need square brackets and double quotes as you mentioned?

Also couple of things:

1) I believe that document.getElementById("UserResults").innerHTML=returnText;
 instead should be document.getElementById("UserResults").innerHTML=result;


2) Regarding (var key in myarray), assuming that myarray is ["1-john.Smith","2-Adam.smith","3-Peter.smith"], then I believe 'result' String will be:

<select name='results'/>
<option value="1">john.smith </option>
<option value="2">adam.smith </option>
<option value="3">peter.smith </option>

Have we closed the <Select> tag correctly?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
chaitu chaitu

1)yes

2)
   var result = "<select name='results'>";

    for (var key in myarray) {
        result += "<option value="+myarray[key].split("-")[0]+">"+myarray[key].split("-")[1]+"</option>";
    }
 result +="</select>";
		document.getElementById("UserResults").innerHTML=result;

Open in new window

GlobalDictator

ASKER
@chaituu,

Thanks, I'll give it a go and let you know.

Cheers
GlobalDictator

ASKER
@chaituu,

If the return string is exactly like :
["1-john.Smith","2-Adam.smith","3-Peter.smith"]

then the select tag gets build as:

<select name='results'>
     <option value=[>undefined</option>
     <option value=">undefined</option>
    <option value=1>undefined</option>
    <option value=></option>
    <option value=j>undefined</option>
    <option value=o>undefined</option>
    <option value=h>undefined</option>
    <option value=n>undefined</option>
    <option value=.>undefined</option>
    <option value=S>undefined</option>
    <option value=m>undefined</option>
    <option value=i>undefined</option>
    <option value=t>undefined</option>
    <option value=h>undefined</option>
    <option value=">undefined</option>
    <option value=,>undefined</option>
    <option value=">undefined</option>
    <option value=2>undefined</option>
    <option value=></option>
    <option value=A>undefined</option>
    <option value=d>undefined</option>
    <option value=a>undefined</option>
    <option value=m>undefined</option>
    <option value=.>undefined</option>
    <option value=s>undefined</option>
    <option value=m>undefined</option>
    <option value=i>undefined</option>
    <option value=t>undefined</option>
</select>

Can you please suggest whats wrong here?

Thanks
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
chaitu chaitu

run this dummy html in browser and see the result.
dummy.html
GlobalDictator

ASKER
I've tried and it seems to work fine if I hard code myarray. But when I use the output from the String Buffer (and I've checked the return with an alert), it doesnt seem to work.

var result = "<select name='results'>";
	    for (var key in properText) {
	    	alert("The Key with Proper is:" +properText[key]);
	    	alert("The Key without Proper is:" +key);	    	
	        result += "<option value="+properText[key].split("-")[0]+">"+properText[key].split("-")[1]+"</option>";
	    }
	    result +="</select>";
	    alert("The result is: " + result);

Open in new window


I get the following :
The Key without Proper is:[
The Key without Proper is:0

The Key without Proper is:"
The Key without Proper is:1

The Key without Proper is:j
The Key without Proper is:2

The Key without Proper is:o
The Key without Proper is:3

The Key without Proper is:h
The Key without Proper is:4

The Key without Proper is:n
The Key without Proper is:5

The Key without Proper is: .
The Key without Proper is:6

and so on until the last character.

Can you please sugest and help whats wrong here.

Thanks
chaitu chaitu

i think you are not getting proper array from server side.first print properText in java

print properText here.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
GlobalDictator

ASKER
@chaituu

I've printed the string that has been build both on the Java end and in the Javascript and it looks fine ie: ["1-john.smith","2-adam.smith", "3-peter.smith",]

Can you confirm that the below code to write a string buffer is ok or is this where the problem is?  

StringBuffer[] stringBuffer = new StringBuffer[userDTOList.size()];							
for (UserIdDTO userDTO : userDTOList) {
	for(int i=0; i<userDTOList.size(); i++) {
		stringBuffer[i] = new StringBuffer();
		stringBuffer[i].append(responseValue(userDTO));
                                i++;
	}
}			
sendResponse(response.getWriter(), stringBuffer); 
} 
			
private StringBuffer responseValue(UserIdDTO userDTO){
	StringBuffer strBuffer = new StringBuffer();
	strBuffer.append(userDTO.getId());
	strBuffer.append(" - ");
	strBuffer.append(userDTO.getuserName());		
	return strBuffer;
}	
	
public static void sendResponse(PrintWriter writer, StringBuffer[] stringBuffer) {
	if (stringBuffer != null) {			
		for(int i=0; i<stringBuffer.length; i++) {				
			if(null!=stringBuffer[i]) {
				writer.write(stringBuffer[i].toString());
			}	
		} else {
			// TODO write to log			
		}		

Open in new window

GlobalDictator

ASKER
@chaituu

If I hard code the value as ["1-john.Smith","2-Adam.smith","3-Peter.smith"]; in my JS, then the split works fine.

But if I'm getting exactly the same value as the output from the StringBuffer from the java code, then the for (var key in properText) loop to split the string doesnt work. Putting alerts inside the for loop like below

for (var key in properText) {
	    	alert("The Key with ProperText is:" +properText[key]);
	    	alert("The Key without ProperText is:" +key);

Open in new window


gives me the following output:

The Key with ProperText is:[
The Key without ProperText is:0

The Key with ProperText is:"
The Key without Proper is:1

The Key with ProperText is:-
The Key without Proper is:2

The Key with ProperText is:j
The Key without Proper is:3

until........
The Key without Proper is:]
The Key without Proper is:28


The loop considers each character as independent value for each position in the 'key'. Can you please help here?

Thanks
ASKER CERTIFIED SOLUTION
chaitu chaitu

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
GlobalDictator

ASKER
OK, I'll implement these changes and let you know.

But I think the fact that we are passing a String from Java and in Javascript we are treating that String as an Associated Array could be the potential problem you think? I think the Javascript is treating that string as an array of characters instead!!

Your thoughts??
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
chaitu chaitu

we are sending thes string of associative array to JS and displaying it.i have tried it at my end and its working fine.
GlobalDictator

ASKER
OK let me implement this change and I'll let you know