I have 2 combobox(select) on html page and i want to populate data in second combobox based on data selected in first combobox by user.I am using jsp and ajax for that.I have Ajax code but i dont know how to return data in combobox from server side jsp page..

Please help me.Give me jsp code.
//////////////////////html file

<html>
<head>
<script src="selectcustomer.js"></script>
</head>
<body>
<form> 
Select a Customer:
<select name="customers" onChange="showCustomer(this.value)" >
  <option value="ALFKI">Alfreds Futterkiste</option>
  <option value="NORTS ">North/South</option>
  <option value="WOLZA">Wolski Zajazd</option> 
</select>
<select name="id" id="id">
 <option value="A">a</option>
<div id="txtHint"></div>
 </select>
</form>
<p>
</p>
</body>
</html>

///////////////////////////ajax file()

var xmlHttp

function showCustomer(str)
{ 
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 
var url="getinfo.jsp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged() 
{ 
if (xmlHttp.readyState==4)
{ 
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

//////////jsp file(getinfo.jsp)[Not working..]

<%String name=(String)request.getParameter("q");
String sid=(String)request.getParameter("sid");
out.print("<option>"+name+"</option>");
out.print("<option>"+sid+"</option>");
%>

////////////////

help me for this jsp file....how can i return data to second combobox

Dani AI

Generated

The real problem in the original thread is HTML + injection technique, not Ajax itself. Post #1 placed a DIV inside a SELECT (invalid HTML), and the script injected server output into that DIV — browsers handle that unpredictably. Post #2 () shows a working workaround that returns a whole SELECT from the server, but replacing the entire element is brittle (event handlers and form wiring can be lost). A more robust approach is: keep the target <select> in the page, have the server return structured data (JSON), and update the existing select by creating <option> nodes.

Modern client-side pattern (creates options via DOM instead of innerHTML):

function populateOptions(customerId) {
  const sel = document.getElementById('id'); // existing select
  fetch('getinfo.jsp?q=' + encodeURIComponent(customerId))
    .then(resp => { if (!resp.ok) throw new Error(resp.status); return resp.json(); })
    .then(items => {
      sel.length = 0; // clear options
      items.forEach(it => {
        const o = document.createElement('option');
        o.value = it.value;
        o.textContent = it.label;
        sel.appendChild(o);
      });
    })
    .catch(err => { console.error(err); sel.length = 0; });
}

Minimal JSP example that emits JSON (scriptlet style shown only for clarity; prefer a JSON library like Gson in production):

<%
String q = request.getParameter("q");
response.setContentType("application/json;charset=UTF-8");
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append("{\"value\":\"1\",\"label\":\"Option for ").append(q).append(" A\"},");
sb.append("{\"value\":\"2\",\"label\":\"Option for ").append(q).append(" B\"}");
sb.append("]");
out.print(sb.toString());
%>

Troubleshooting and cautions: ensure the select has an id and contains only option/optgroup children; use encodeURIComponent for query values; in script use & (not &amp;) when building query strings; prefer creating DOM nodes to avoid XSS from raw HTML; check the browser Network tab to verify the server response and Content-Type; and use XHR fallback if very old browsers must be supported. This approach keeps markup valid and makes the client/server contract clear and maintainable.

i got solution for that.....
something like that ..it works....

<%String name=(String)request.getParameter("q");
String sid=(String)request.getParameter("sid");
%>
<select name="info">
 <option ><%=name%></option>; 
<option >0</option>;
</select>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.