My task involves using an AJAX function call to return an ArrayList and populate the results in an HTML dropdown list. However, I have encountered a problem as my dropdown list remains empty despite my efforts.
Here is my servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer p = Integer.parseInt(request.getParameter("studentid"));
ArrayList<SessionDataBean> result = new ArrayList<>();
String sessid = null;
try ( Connection con = JdbcUtil.getConnection()) {
String sql= "select distinct F.SESSIONID "
+ "from Students F "
+ "where F.studentid = "+p;
try (Statement st = con.createStatement()) {
System.out.println(sql);
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
result.add(new SessionDataBean(rs.getString(1)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
response.setContentType("application/json");
new Gson().toJson(result, response.getWriter());
}
The AJAX function call code is as follows:
function listSession(){
var name = document.getElementById("studentid").value;
$.ajax({
url : "<%=context%>/ListSessionsServlet?studentid=" + name,
type : "POST",
async : false,
dataType: "json",
success : function(data) {
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option>'+o.id+'</option>'; <---issue might be here?
});
$('#sessid').append(toAppend);
}
});
}
Lastly, here is the HTML code for displaying the dropdown list:
<div class="cell">
Select Session for Student
<div class="input-control select mutiple full-size">
<select id="sessid" name="sessid">
</select>
</div>
</div>