What I basically what to do is to read an ID from user, pass it to a servlet using AJAX and then fetch the corresponding book name and course from database and then display them in respective textboxes. AJAX is like rocket science to me and I have just started from some basic online tutorials. Here's the code I have written:
JSP code:
<body>
Edit book details:</br>
Enter Book Id: <input type="text" id="tb1" onkeyup="get(this.value)"/></br>
Book name is: <input type="text" id="tb2"/></br>
Course is: <input type="text" id="tb3"/></br>
</body>
JS code:
<script>
function get(str)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("tb2").value=xmlhttp.responseText;
document.getElementById("tb3").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Demo?q="+str,true);
xmlhttp.send();
}
</script>
Servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String str=request.getParameter("q");
String book,course;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(url,user,pass);
PreparedStatement ps=con.prepareStatement("select bname,course from product where pid=?");
ps.setString(1,str);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
book=rs.getString(1);
course=rs.getString(2);
}
else
{
book="";
course="";
}
response.getWriter().write(book);
response.getWriter().write(course);
}
catch(Exception e)
{
e.printStackTrace();
}
}
The problem is that the results are both shown in same textbox(upper screenshot) and I want it to be like the lower one.
Yes, I know the problem is that I am writing document.getElementById("tb2").value=xmlhttp.responseText;
document.getElementById("tb3").value=xmlhttp.responseText;
And that's what I am asking, how do I filter the responseText
according to requirements?