AJAX autocomplete textbox in Java web technology (JSP and servlets)

29,242

@user2870719 You can try like following, In your jsp page send a ajax request to a servlet/jsp and fill the response data in a javascript variable. So you can get the jQuery autocomplete textbox as i mentioned above.

<%@page import="java.sql.*"%>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
 </script>
<script type="text/javascript">
function showData(value){ 
$.ajax({
    url : "ur_servlet?name="+value,
    type : "POST",
    async : false,
    success : function(data) {
//Do something with the data here
    }
});
}
</script>
</head>
<body>
<form name="employee">
<input type="text" name="name" id="name" onkeyup="showData(this.value);"><br>


</table>
</body>
</html>

And in servlet,

String name = request.getParameter("name");
String buffer="";  
try{
   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
   Statement st=con.createStatement();
   ResultSet rs=st.executeQuery("select * from data where name like '"+name+"%'");
    while(rs.next())
    {
    buffer=buffer+"'"+rs.getString("name")+"',";
    }
response.getWriter().println(buffer);
}
 catch (Exception e) {
    e.printStackTrace();
 }

Finally send the response to jsp page. Let me know if this helps..

Share:
29,242
Admin
Author by

Admin

Updated on March 22, 2020

Comments

  • Admin
    Admin about 4 years

    Please I need your assistance on how to make HTML input text element work like "Google's AJAX search engine" input text element with Java web technology (JSP, servlets and AJAX). Data on the drop-down list will be from a database table, e.g MySQL or Microsoft SQL databases respectively.

    I studied the NetBeans tutorial on this, but selecting a value from the drop-down list to appear in the HTML input text element isn't possible with that tutorial. Here's the link.

    Thanks.