I am currently working on implementing a dependent drop-down list feature. I have developed a JSP page where I call a servlet through an AJAX request. In the servlet, I use a JSON object to retrieve values for the dropdown list. While the values are being properly retrieved in the JSON object, I am facing an error where the request is not completing successfully (the error method is triggered instead of the success method).
Below is my AJAX code:
$.ajax({
type: "GET",
url: "MyServlet?index="+listindex,
datatype: 'JSON',
error: function() {
alert("Error");
},
success: function(data) {
try{
var citiArray = JSON.parse(data);
if(citiArray != null){
for(var s=0; s<citiArray.length; s++){
var serial = citiArray[s];
//populating the drop-down list
$("#dname").append($("<option></option>").val(serial.authors1).html(serial.authors1));
}
}
} catch(err){
alert(err);
}
}
});
My Servlet code: MyServlet.java
public class MyServlet extends HttpServlet {
/**
* @see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/orcl" ,"hr", "password");
request.setCharacterEncoding("utf8");
response.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String listindex = request.getParameter("index");
out.print(listindex);
String query2 = "select module from course where cname=?";
PreparedStatement st2 = con.prepareStatement(query2);
st2.setString(1,listindex);
ResultSet rs2 = st2.executeQuery();
JSONArray uniList1 = new JSONArray();
while(rs2.next()) {
uniList1.add(rs2.getString("module"));
//System.out.println(rs2.getString("module"));
}
JSONObject obj = new JSONObject();
obj.put("key", uniList1 );
System.out.println(obj);
out.print(obj);
} catch(Exception e) {
e.printStackTrace();
}
}
}
web.xml:
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.dac.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
Thank you, Rohit