hi all!
i am new to jsp, i have two comboboxes,in which values of 2nd combo box are linked two first combo box and we get values for both these boxes from database.

table1

(pk)itemno:text
itemname:text (no duplicates)

table2

(pk)itemno:text(duplicates)
(pk)pcode:text
pname:text(no duplicates)

i want to display..

combobox1:itemname
combobox2:pname

Note: Both Values of combobox are to be retrieved from database.

when user select itemname corresponding values of pname should be displayed. I went through google and some threads of this forum and found some info but there option values are not retrieved from database(given in code itself), but i'm puzzled from retrieving 1st combo values and select one to retrieve the values of 2nd combo.

Hope i have made my question clear. Thank You all!

Can I see you code please? Start to code and post your problems. Definitely, we will help you.

Can I see you code please? Start to code and post your problems. Definitely, we will help you.

Many thanks. Well i started coding and succesful in retrieveing first combox values from database and stored the selected value in a hidden type input now i dunno know to proceed frm here.

my problem is that, i will use <form action="servlet "> and retrieve values from database using selected value in combobox1 (getParameter()).now how can i send back these reteieved values of combobox 2 back to jsp...??

my code trail.jsp

<%@ page language="java" contentType="text/html" import="java.sql.*" %>

<html>
<head><title>select  box demos</title>
<script type="text/javascript">
function redirect()
{
 var index=document.myForm.selbox.selectedIndex;
 document.myForm.selv.value=document.myForm.selbox.options[index].value;
document.write(document.myForm.selv.value);// stored selected value in hidden type value
}

</script>
</head>
<body>
<form name="myForm">
<table>
<%
 try
 {
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  Connection conn=DriverManager.getConnection("jdbc:odbc:trail");
  try
  {
   String itname[]={};
   
   int i=0,j=0,m=0;

   String str1="select * from table1";
   PreparedStatement stmt1=conn.prepareStatement(str1);
   ResultSet rs1=stmt1.executeQuery();

   itname=new String[100];
 
   while(rs1.next())
   { 
    itname[m]=rs1.getString(2);
    m++;
   }
    
   
   for(j=m;j<100;j++)
   {
    itname[j]="null";
   }
   

  out.println("<tr>");
  out.println("<td>Item Type:</td>");
  out.println("<td>"); 
%>
 <select name="selbox" id="sel" onchange=redirect(this.form) >
<%
  while(i<itname.length)
  {
   if(itname[i]!="null")
    out.println("<option value="+itname[i]+">"+itname[i]+"</option>");
    i++;
  }
  out.println("</select>");

  }
  catch(SQLException e)
  {
   out.print("SQL Not Executing");
  }
 } 
 catch(Exception e)
 {
  e.printStackTrace();
 }
%>
<input type="hidden" name="selv" >
</table>
</form>
</body>
</html>

Use Ajax for your reqirement

i am giving solution to your problem

first create 2 jsp for your reqirement

first you show the one list itemname in the first jsp page
when user select the option from the list ,call ajax function in the
first jsp page ,and reterieve the value from the database according
to the itemname
i show the code
this is your first jsp page itemname.jsp

<html>
<head>






</head>



<body>
<script type="text/javascript">function ajaxFunction()
{var xmlHttp;
try
  {  // Firefox, Opera 8.0+, Safari 
   xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {  // Internet Explorer 
   try
    {    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    }
  catch (e)
    {    try
      {      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      }
    catch (e)
      {      alert("Your browser does not support AJAX!");      return false;      }    }  }
  xmlHttp.onreadystatechange=function()
    {
	   //alert("i m  not  in ready state");
	   
	    if(xmlHttp.readyState==0)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    alert("The request is not initialized");
	  
	   

	   
	  
      }
	      if(xmlHttp.readyState==1)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    alert("The request has been set up");
	  
	   

	   
	  
      }
	  
	  
	  
	        if(xmlHttp.readyState==2)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    alert("The request has been sent");
	  
	   

	   
	  
      }
	  
	  	        if(xmlHttp.readyState==3)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    alert("The request is in process");
	  
	   

	   
	  
      }
	   
	  
	   
	  
	  
	   
	   
	  
    if(xmlHttp.readyState==4)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    //alert("i m in ready state");
	  
	   document.getElementById("theResponse").innerHTML = xmlHttp.responseText;

	   
	  
      }
    }
	      var itemname=document.myForm.itemname.value;
	      var url="getProduct.jsp";
          url=url+"?itemname="+itemname+"&sid="+Math.random();
          //url=url+"&sid="+Math.random();

	
	  
         xmlHttp.open("GET",url,true);
         xmlHttp.send(null); 
   }
  
  </script>
select itemname:<form name="myForm" onBlur="ajaxFunction();" >
  <select  name="itemname">
  <option value="computer">computer</option>
  <option value="cars">Cars</option>
  
  </select>

<div id="theResponse">

</div>
</form></body>
</html>

Now your second Jsp page
getProduct.jsp

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>

<%
// open the database connection and get the ResultSet
// according to your itemname
 // take example 
// ResultSet rs=select pname from product where itemname='"+request.getParameter(itemname)+"' ;

%>
 <select  name="pname">

<%   while(rs.next())
   { %>
    <option value="<%=rs.getString(1)%>">"<%=rs.getString(1)%>"</option>
   
 <%  } %>

 </select>
 
 
     





%>



</body>
</html>

try it

Promise me that you will the follows Peter budo's post.

A code I am posting here is a solution of your current problem. It can't help to solve your Java Web Development problems.

DB.java - Place this java file in WEB-INF/classes folder and compile it.

package com.me;

import java.sql.*;
import java.util.*;

public class DB
{
   static String url="jdbc:odbc:sampledb";
   static String username="your_user_name";
   static String password="your_password";
   static String driver="sun.jdbc.odbc.JdbcOdbcDriver";
    static{
         try {
                 Class.forName(driver);
             }catch(Exception ex) {}
   }
  public static Connection getCn() throws Exception {
         return DriverManager.getConnection(url,username,password);  
  }
  public static int execute(String sql) throws Exception {
         Connection cn=getCn();
         Statement st=cn.createStatement();
         int i=st.executeUpdate(sql);
         st.close(); cn.close();
         return i;
  }
  public static Object getValue(String sql) throws Exception{
         Connection cn=getCn();
         Statement st=cn.createStatement();
         ResultSet rs=st.executeQuery(sql);
         Object i=null;
          if(rs.next())
                i=rs.getObject(1);
         rs.close();
         st.close(); cn.close();
         return i;
  }
  
  public static String getCombo(String sql,String sel) throws Exception{
         Connection cn=getCn();
         Statement st=cn.createStatement();
         ResultSet rs=st.executeQuery(sql);
         if(sel==null) sel="";
         
         String result="<option value=''>Select</option>";
         String value="";
         String text="";
         while(rs.next()){
                value=rs.getString(1); text=rs.getString(2);
 
                if(value.equals(sel)) {
                  result=result + "<option value=\"" + value + "\"  selected=\"selected\" >" + text + "</option>";

                }
                else{
                   result=result + "<option value=\"" + value + "\">" + text + "</option>";

                } 
          }
         rs.close(); st.close(); cn.close();  
         return result;
   }
}

and a page1.jsp

<?% page language="java" import="java.sql.*" %>

<%
   String item=request.getParameter("item");
   if(item==null) item="";

%>
<form name="form1" method="post" action="page1.jsp">
   <select name="item"  onchange="form1.submit()">
       <%=com.me.DB.getCombo("select itemno,itemname from item",item) %>
   </select>

   <select name="prod">
        <%=com.me.DB.getCombo("select pcode,pname from product where itemno='" + item + "'",item) %>
   </select>
</form>

Use Ajax for your reqirement

i am giving solution to your problem

first create 2 jsp for your reqirement

first you show the one list itemname in the first jsp page
when user select the option from the list ,call ajax function in the
first jsp page ,and reterieve the value from the database according
to the itemname
i show the code
this is your first jsp page itemname.jsp

Thank You amarjeetsingh for spending your valuable time on answering this.

well i heared AJAX will solve the problem but i have no time (deadline of this project) to learn AJAX. So, looking for other alternative, anyway i managed to get through your code and going to work on it.

</script>
select itemname:<form name="myForm" onBlur="ajaxFunction();" >
<select name="itemname">
<option value="computer">computer</option>
<option value="cars">Cars</option>

</select>

Seems like you have given values directly , i want these values from database too. Wat's the job of this AJAX Script u given? .
Does it gets values for itemname from database?

Once again Many Thanks.Added Reputation.

Thank you adatapost , with your motivation i started coding and it's very kind of you for helping me to solve this.

Promise me that you will the follows Peter budo's post.

Sure, I Promise.

A code I am posting here is a solution of your current problem. It can't help to solve your Java Web Development problems.

what kind of java web development problems?

I have seen your code and not familiar with some lines anyway got some sense of it, i will get back to you as soon as i run this code.

Thanks for Spending your valuable time.Added Reputation.

you want to show the itemname from the database
it is very easy,

in your servlet
by open a dao connection
get all the data from the database
set into the ArrayList
then in the servlet
set the ArrayList

request.setAttribute("arr",ArrayList);

now
in the jsp

<select name="itemname">
<c:forEach   items="${arr}"   var="show" >
 <option value=" ${show}">${show}</option>


</c:out>


</c:forEach>

</select>

but it will be in your first jsp page

then use the Ajax in the first jsp page for the second jsp page

Hai adatapost compiled ur java code but no results it gives Http status 500 error...anyway Thanks 4 ur effort.

Just now finished tutorial on AJAX now i'm moving to amarjeetsingh's AJAX code...will be back after testing it!!!

hi amarjeetsingh i have coded as you said

2 Jsp pages
itemname.jsp
getproduct.jsp

the problem here is the value of itemname selected was not sent to secondpage (request.getparameter not working) this is wat i get when i run the code
[IMG]http://i43.tinypic.com/dwqve1.jpg[/IMG]

i am giving you the 2 jsp pages and access database Zipped and i put them in attachment down here, Could u please help me to run this code, i would be very greatful to you.

Thank You,
sriups

Once you decide to follow MVC standard, you can contact me.
Secondly you should start learning about basic deployment with Tomcat

of course i follow mvc standard i'm using jbdc inside jsp here just for testing purpose i'm going to convert it to MVC standard later.

of course i follow mvc standard i'm using jbdc inside jsp here just for testing purpose i'm going to convert it to MVC standard later.

You should do it from beginning, that way you wouldn't be pulling double shift and same goes for us

the best answer is ajax and actually you do not to learn ajax just copy
the code i will gave and follow the guidlines copy and paste the attached file into your project folder :

1- copy and paste the attached file into your project folder


2- copy the following code and paste into the head of you jsp file

<script type="text/javascript" src="prototype.js"></script>
<script>
function item_code1(value){

var myAjax1=new Ajax.Request('itemcode1.jsp',{
method: 'post',postBody:'id='+value, onSuccess: function(transport) {
var itemcode1=$('itemcode1');
itemcode1.update(transport.responseText);
}
});
}

3- in your itemname combobox html make it exactly like follow <select name="itemname1" size="1" id="first1" onchange="item_code1($('first1').value);"> 4- copy and paste the following code where do you want the itemcode to be appeare <div id="itemcode1"> </div> 5- now you just need to open new jsp file and copy write the following

<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %> 


<%
String id=request.getParameter("id");
Vector v1,v2;

jmm.Database database = new jmm.Database(pageContext.getServletContext().getRealPath("/WEB-INF/config.txt")); // depend on  yours 
database.jdbcConnect();
String sql;

sql = "select itemcode from item where itemname='"+id+"'";



out.print("<select name=itemcode1 id=\"itemcode \">");

 v1=database.jdbcMultipleRowQuery(sql);
 if(v1.size()!=0){
	for(int i=0;i<v1.size();i++){
	v2 = (Vector)v1.elementAt(i);
			for(int j=0;j<v2.size();j++){
				out.print("<option>"+v2.get(0)+"</option>");				
			}
	}
	out.print("</select>");
	
	}else{
	
	}




database.jdbcConClose();
database = null;

%>

5- i wish it will help ,

Attachments
/*  Prototype JavaScript framework, version 1.5.1.1
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.1.1',

  Browser: {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      (document.createElement('div').__proto__ !==
       document.createElement('form').__proto__)
  },

  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) { return x }
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  toJSON: function(object) {
    var type = typeof object;
    switch(type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return object.toString();
    }
    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (object.ownerDocument === document) return;
    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (value !== undefined)
        results.push(property.toJSON() + ': ' + value);
    }
    return '{' + results.join(', ') + '}';
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [event || window.event].concat(args));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    return this.toPaddedString(2, 16);
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  },

  toPaddedString: function(length, radix) {
    var string = this.toString(radix || 10);
    return '0'.times(length - string.length) + string;
  },

  toJSON: function() {
    return isFinite(this) ? this.toString() : 'null';
  }
});

Date.prototype.toJSON = function() {
  return '"' + this.getFullYear() + '-' +
    (this.getMonth() + 1).toPaddedString(2) + '-' +
    this.getDate().toPaddedString(2) + 'T' +
    this.getHours().toPaddedString(2) + ':' +
    this.getMinutes().toPaddedString(2) + ':' +
    this.getSeconds().toPaddedString(2) + '"';
};

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function(){
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (hash[key].constructor != Array) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  times: function(count) {
    var result = '';
    for (var i = 0; i < count; i++) result += this;
    return result;
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  },

  toJSON: function() {
    return this.inspect(true);
  },

  unfilterJSON: function(filter) {
    return this.sub(filter || Prototype.JSONFilter, '#{1}');
  },

  isJSON: function() {
    var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  },

  evalJSON: function(sanitize) {
    var json = this.

CoSIS1>the best answer is ajax and actually you do not to learn ajax just copy the code i will gave and follow the guidlines copy and paste the attached file into your project folder.

How did you know AJAX? just copy the code?

Wrap up source code with bb code tags.
Read
How to use BB code tags?

am new member here, and i just wanted to help here
plus this code is working , i have used it before .
actually i know some in ajax that helped me before in my projects

<html>
<head><title>Sales Page/title></head>
<body>
<script type="text/javascript">
function ajaxFunction()
{
 var xmlHttp;
 try
 {  // Firefox, Opera 8.0+, Safari 
   xmlHttp=new XMLHttpRequest();
 }
 catch (e)
 {  // Internet Explorer 
   try
   {    
     xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    
   }
   catch (e)
   {    
     try
     {      
       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      
     }
     catch (e)
     {      
       alert("Your browser does not support AJAX!");      
       return false;      
     }    
   }  
 }
 
 xmlHttp.onreadystatechange=function()
 {
   //alert("i m  not  in ready state");
	   
   if(xmlHttp.readyState==0)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     alert("The request is not initialized");
   }
   if(xmlHttp.readyState==1)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     alert("The request has been set up");
   }
   if(xmlHttp.readyState==2)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     alert("The request has been sent");
   }
   if(xmlHttp.readyState==3)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     alert("The request is in process");
   }
   if(xmlHttp.readyState==4)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     //alert("i m in ready state");
     document.getElementById("theResponse").innerHTML = xmlHttp.responseText;
   }
 }
	      
	      
 var itemname=document.myForm.itemname.value;
 var url="getProduct.jsp";
 url=url+"?itemname="+itemname+"&sid="+Math.random();  //url=url+"&sid="+Math.random();

 xmlHttp.open("GET",url,true);
 xmlHttp.send(null);
}
</script>
select itemname:
<form name="myForm">
/*
  wrong code------
  <option>processors</option>
<option>speakers</option>
<option>monitor</option>
<option>mouse</option>

due to this code you can not get
the value in the request.getParameter("itemname");

*/

<!-- right code   --->

<select  name="itemname" onChange="ajaxFunction();">
<option value="processors">processors</option>
<option value="speakers">speakers</option>
<option value="monitor">monitor</option>
<option  value="mouse">mouse</option>





</select>
<div id="theResponse">

</div>
</form></body>
</html>

Now your second page getproduct.jsp

i have removed un necessary code

<%@ page language="java" contentType="text/html" import="java.sql.*" %>

<html>
<head><title>select  box demos</title></head>
<body>

<%
 try
 {
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  Connection conn=DriverManager.getConnection("jdbc:odbc:select");
  try
  {

   String val=request.getParameter("itemname");

   //String val1="speakers";
   //String val2="processors";
   

  // String itname[]={};
   
 //  int i=0,j=0,m=0; 

   String str="select * from stocks where item_name=?";

   PreparedStatement stmt=conn.prepareStatement(str);

   stmt.setString(1,val);

   ResultSet rs=stmt.executeQuery();

  /*   itname=new String[100];
 
   while(rs.next())
   { 
       itname[m]=rs.getString(3);
        m++;
   }
    
   
   for(j=m;j<100;j++)
   {
    itname[j]="null";
   }  */
    
%>

Prod Name:  <select name="productname">
<%
  while(rs.next())
  {
   //  if(itname[i]!="null")
       out.println("<option value="+rs.getString(3)+">"+rs.getString(3)+"</option>");
      //i++;
  }
     // out.println("</select>");

  }
  catch(SQLException e)
  {
      out.print("SQL Not Executing");
  }
 } 
 catch(Exception e)
 {
  e.printStackTrace();
 }
 
   finally
	        	  {
	        		  
	        		  
	        		  try
	        	    	{
	        	    	    if(rs!=null)
	        	    	      {
	        	    	     	     rs.close();
	        	    		         rs=null;
	        	    		        	    		
	        	    	      }
	        	    	     if(stmt!=null)
	        	    	      {
	        	    	     	     stmt.close();
	        	    		          stmt=null;
	        	    		        	    		
	        	    	      }
	        	    	     
	        	    	     if(conn!=null)
	        	    	      {
	        	    	     	     conn.close();
	        	    		          conn=null;
	        	    		        	    		
	        	    	      }
	        	    	     
	        	    	   
	        	    	 }catch(SQLException e)
	        	    	 {
	        	    	 	 out.print("SQL Not Executing"+e);
	        	    	 }
	        	    	
	        		  
	        		  
	        		  
	        	  }
	        	 
 
 
%>
</select>

</body>
</html>
This article has been dead for over six months. Start a new discussion instead.