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

GlobalDictator
GlobalDictator used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
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
  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

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 .
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
@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.

Author

Commented:
@chaituu,

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

Thanks
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

put alert and see how your string is coming out.

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

Author

Commented:
@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?
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

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

Author

Commented:
@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.

Author

Commented:
@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?
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

Author

Commented:
@chaituu,

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

Cheers

Author

Commented:
@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
run this dummy html in browser and see the result.
dummy.html

Author

Commented:
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
i think you are not getting proper array from server side.first print properText in java

print properText here.

Author

Commented:
@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

Author

Commented:
@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
your action class code should be like this;you have written some unneccassary code;

               StringBuffer sbr = new StringBuffer();
	ArrayList<UserIdDTO> userDTOList = new ArrayList<UserIdDTO>();
					
			UserIdDTO userDT1=new UserIdDTO();
			userDT1.setId("1");
			userDT1.setUserName("john.Smith");
			
			userDTOList.add(userDT1);
			
			UserIdDTO userDT2=new UserIdDTO();
			
			userDT2.setId("2");
			userDT2.setUserName("Adam.smith");
			
			userDTOList.add(userDT2);

			UserIdDTO userDT3=new UserIdDTO();
			
			userDT3.setId("3");
			userDT3.setUserName("Peter.smith");

			userDTOList.add(userDT3);
			sbr.append("[");
			
			for (UserIdDTO userDTO : userDTOList) {
				sbr.append(responseValue(userDTO)+",");
			}
		
			sbr.deleteCharAt(sbr.toString().lastIndexOf(","));
			sbr.append("]");
			
			System.out.println(sbr.toString());
			
			response.getWriter().write(sbr.toString());

Open in new window

Author

Commented:
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??
we are sending thes string of associative array to JS and displaying it.i have tried it at my end and its working fine.

Author

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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial