Implement Auto suggest in JSP using Ajax call in Jquery

This solution is: When user enters any data on the input field, the entered data is taken and using ajax call servlet method will be triggered, which returns the matched records in DB as JSON string. Then the response data will be shown as suggestion under input text field.

Files Created to implement this functionality:

autoSuggest.jsp, searchServlet.java.

Code for autoSuggest.jsp:


<!DOCTYPE html>
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
         <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
  var val = $("#project").val();
  var projects;

    $( "#project" ).autocomplete({
      minLength: 1,
      source: function( request, response ) {
       $.ajax({
            type: "Get",
            url:"searchservlet",            
            contentType : "application/json", dataType : 'json',
            data:{"empName":$("#project").val()},
            success: function(data){
                projects = data;
                response(data);
            },
            failure: function(){
                alert("failed..");
            }
         });
      },
      focus: function( event, ui ) {
        $( "#project" ).val( ui.item.EmpName );
        return false;
      },
      select: function( event, ui ) {
        $( "#project" ).val( ui.item.EmpName );        
        return false;
      }
    })  
   
    .data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("
	<li style='font-size:16px;color:#777;padding:1px;'>")
                    .data("ui-autocomplete-item", item)
                    .append("<a> " + item.EmpName + "
 </a>")
                    .appendTo(ul);
            };
            
    /*  [This code also works similar as above [you can change the item name. But you have to use only "instance" with .autocomplete or
     * "ui-autocomplete" with .data] 
    * .autocomplete( "instance" )._renderItem = function( ul, listitem ) {
      return $( "
	<li>" )
        .append( "
<div>" + listitem.EmpName + "
" + "</div>
" )
        .appendTo( ul );        
    };*/        
  } );
  </script>
</head>
<body>
<div id="project-label">Search an Employee (type "E" for a start)::</div>
<input style="padding:10px;font-size:18px;margin:10px;" id="project">
<!--<input type="hidden" id="project-id"> -->
</body>

</html>

searchServlet.java


package model;

import java.io.IOException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@WebServlet(name = "searchServlet", urlPatterns = { "/searchservlet" })
public class searchServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

public void init(ServletConfig config) throws ServletException {
super.init(config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("entered servlet...");
String empName = request.getParameter("empName").concat("%");
System.out.println("request value:"+empName);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
PreparedStatement ps = conn.prepareStatement("select empname from emp where empname like ? order by empname");
ps.setString(1, empName);
ResultSet rs = ps.executeQuery();
JSONArray jarray = new JSONArray();

int i =1;
while(rs.next()){
JSONObject jobj = new JSONObject();
String lable = "EmpName";
jobj.put(lable, rs.getObject(1));
jarray.add(jobj);
i++;
}

String JsonString = jarray.toJSONString();
System.out.println("JsonString:"+JsonString);
conn.close();
response.getWriter().write(JsonString);
} catch (Exception e) {
}

}
}

 

UI Page:

3

 

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s