hey U guys..
I need a jsp code which uses AJAX with dropdowns..
Something like COUNTRY NAME in one dropdown and STATE NAME in the other...
You may select any STATE at first.. Later when we CHANGE the COUNTRY NAME, states of that particular COUNTRY WILL GET REFRESHED IN THE STATE DROPDOWN...
So any text before or after the AJAX section will not be refreshed...
and no php or .net please


Thank you

Dani AI

Generated

Here are focused notes and a minimal JSP+AJAX approach that addresses the common problems in your snippets and gives a concrete, modern pattern to follow. As pointed out, this is guidance to help you fix and learn, not a finished app. Observed pitfalls in 's files: the AJAX URL must match the server endpoint name, do not use HTML entities like "&" inside JS query strings, and the page must be served over HTTP from a servlet container (Tomcat/Jetty) so JSPs are executed.

A tiny JSP that returns a JSON array (place as getStates.jsp in your webapp):

<%@ page contentType="application/json; charset=UTF-8" %>
<%
String country = request.getParameter("country");
String[] states;
if ("USA".equalsIgnoreCase(country)) {
  states = new String[] {"California","Texas","New York"};
} else if ("India".equalsIgnoreCase(country)) {
  states = new String[] {"Maharashtra","Karnataka","Tamil Nadu"};
} else {
  states = new String[0];
}
out.print("[");
for (int i=0; i<states.length; i++) {
  out.print("\"" + states[i].replace("\"","\\\"") + "\"");
  if (i < states.length-1) out.print(",");
}
out.print("]");
%>

Client-side (modern fetch) to populate the second select:

function refreshStates() {
  var country = document.getElementById("country").value;
  fetch("getStates.jsp?country=" + encodeURIComponent(country))
    .then(function(res){ if (!res.ok) throw new Error(res.status); return res.json(); })
    .then(function(states){
      var sel = document.getElementById("state");
      sel.options.length = 0;
      sel.add(new Option(" -- Please Select -- ", ""));
      states.forEach(function(s){ sel.add(new Option(s, s)); });
    })
    .catch(function(err){ console.error("AJAX error:", err); });
}

Quick troubleshooting checklist

  • Load the page via http:// (not file://).
  • Open DevTools Network/Console to see request URL, status (404/500), and response body.
  • Verify endpoint filename and path exactly match the JS URL.
  • Remove any HTML-entity ampersands in JS; use plain & and encodeURIComponent for values.
  • Set JSP content type (shown above) and check server logs (catalina.out) for exceptions.
  • If the page and endpoint are on different hosts/ports, add appropriate CORS headers.

Prefer a small servlet that returns JSON for real apps (keeps logic out of JSP).

Recommended Answers

All 2 Replies

We are not a free pool of slaves. We will help you correct what you have but we will not do it for you.

Sorry for the rude approach..
i did try few things..
can u point why i am not able to get the oupput for this below.. i ve put up all the referred files..

[U][B]file-index.html[/B][/U]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dependant Drop Downs Using Ajax</title>
<meta name="robots" content="noindex, nofollow" />
<script src="js/functions.js" type="text/javascript"></script> 
</head>

<body>

<form>
	<select id="CarMake" name="CarMake" onchange="GetModels();">
		<option value=""> -- Please Select -- </option>
		<option value="Audi">Audi</option>
		<option value="BMW">BMW</option>
		<option value="Ford">Ford</option>
	</select>
        <br>
        <br>
        <br>
        <br>
        <br>
	<select id="CarModel" name="CarModel">
		<option value="">  Please Select  </option>
	</select>
</form>

</body>
</html>

[U][B]file-model.asp[/B][/U]
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<%

strCarMake = request("Make")
strCarModels = ""

select case lcase(strCarMake)

	case "audi"
		strCarModels = "A1||A2||A3||A4||A5"
	case "bmw"
		strCarModels = "Series 1||Series 3||Series 5||Series 6||Series 7"
	case "ford"
		strCarModels = "Ka||Fiesta||Focus||Focus RS||Mondeo"

end select

response.Write(strCarModels)
%>


[U][B]file-function.js[/B][/U]
//Our XmlHttpRequest object to get the models
var xmlModels = getXmlHttpRequestObject();

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	}else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
}

function GetModels(){

	//Get the Car Make
	sltCarMake = document.getElementById("CarMake");
	strCarMake = sltCarMake.options[sltCarMake.selectedIndex].value;
	
	//URL to get the models from, the timestamp is to ensure that
	//each request is fresh, and not cached (especially if data is from the database)
	var timestamp = Number(new Date());
	var url='models.asp?Make=' + strCarMake + '&ts=' + timestamp
	
	//The Ajax Request, the response is handled in the function Models_Handle
	xmlModels.open("GET", url, true);
	xmlModels.onreadystatechange = Models_Handle; 
	xmlModels.send(null);
}

function Models_Handle(){
	if (xmlModels.readyState == 4) {
		
		//Get the Response
		var strResponse = xmlModels.responseText
		
		//Car Model object
		sltCarModel = document.getElementById("CarModel");
				
		//reset select menu to default
		sltCarModel.options.length=0;
		sltCarModel.options[0] = new Option(" -- Please Select -- ","");
		
		if (strResponse != ""){
			
			//Split response into array
			var arrResponse = strResponse.split("||");	
			
			var arrLen = arrResponse.length;
			var intPos = 0;
			for(i=0;i<arrLen;i++){
				sltCarModel.options[i + 1] = new Option(arrResponse[i],arrResponse[i]);
			}
		}		
	}
}
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.