How to get selected value from autocomplete box using ajax

15,584

Solution 1

I have a Servlet like this.

I am trying to return the value to js.

i am not getting the value in js

try {
            String term = request.getParameter("term");
            Class.forName(driverName);
            connection = DriverManager.getConnection(connectionUrl, userId, password);
            System.out.println("Connection Success");
            ps = connection.prepareStatement("SELECT * FROM sample WHERE Name LIKE ?");
            ps.setString(1, term + "%");
            resultSet = ps.executeQuery();
            while (resultSet.next()) {

                data = resultSet.getString("NAME");
                list.add(data);
                System.out.println(resultSet.getString("Name"));

            }

            String searchList = new Gson().toJson(list);
            response.setContentType("application/json");
            response.getWriter().write(searchList);

and also no errors in output console.

Solution 2

You've added only source property to the autocomplete function. You need to add select function for your need.

Prototype should be like this,

$( ".selector" ).autocomplete({
   select: function( event, ui ) {}
});

See the modified code below,

$("#search").autocomplete({     
      source : function(request, response) {
           $.ajax({
                url : "SearchController",
                type : "GET",
                data : {
                       term : request.term
                },
                dataType : "json",
                success : function(data) {
                      response(data);
                }
         });
      },
      select: function( event, ui ) {
         alert( ui.item.value );
         // Your code
         return false;
      }
});
Share:
15,584
FIFA oneterahertz
Author by

FIFA oneterahertz

Actually i am working in a start-up based company,where you have to perform individually and does not depend on others.Basically i dont have that enough technical knowledge or i can say i am not a very good programmer but i feel i can become one of the best programmer by learning and thinking and finally applying the things i get into my mind in the form of code.So Stack Overflow is very good website to understand and also to become a very good programmer.For past 5 months i have been associating with it.Now i am literally addicted to SO.I am improving my programming knowledge and i am willing to share my knowledge to whom so ever and i want to answer as many questions and want to help my fellow programmers.

Updated on June 04, 2022

Comments

  • FIFA oneterahertz
    FIFA oneterahertz almost 2 years

    I am able to display the data from database in a textbox using ajax autocomplete.enter image description here

    I have a requirement like we need to select a name from the names shown below and display the name that we selected using "alert" message. I am posting for what i did.

    index.jsp

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Autocomplete in java web application using Jquery and JSON</title>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <script src="autocompleter.js"></script>
    <link rel="stylesheet" 
      href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
    <!-- User defied css -->
    <link rel="stylesheet" href="style.css">
    
    </head>
    <body>
    <div class="header">
            <h3>Autocomplete in java web application using Jquery and JSON</h3>
    </div>
    <br />
    <br />
    <div class="search-container">
            <div class="ui-widget">
                    <input type="text" id="search" name="search" class="search" />
            </div>
    </div>
    </body>
    </html>
    

    autocompleter.js

    $(document).ready(function() {
         $(function() {
             $("#search").autocomplete({     
                 source : function(request, response) {
                   $.ajax({
                        url : "SearchController",
                        type : "GET",
                        data : {
                               term : request.term
                        },
                        dataType : "json",
                        success : function(data) {
                              response(data);
                        }
                 });
              }
          });
       });
    });
    

    Controller.java

    package com.servlet;
    
    import java.io.IOException;
    import java.util.ArrayList;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.dao.DataDao;
    import com.google.gson.Gson;
    
    public class Controller extends HttpServlet {
            private static final long serialVersionUID = 1L;
    
            protected void doGet(HttpServletRequest request,
                    HttpServletResponse response) throws ServletException, IOException {
    
                    response.setContentType("application/json");
                    try {
                            String term = request.getParameter("term");
                            System.out.println("Data from ajax call " + term);
    
                            DataDao dataDao = new DataDao();
                            ArrayList<String> list = dataDao.getFrameWork(term);
    
                            String searchList = new Gson().toJson(list);
                            response.getWriter().write(searchList);
                    } catch (Exception e) {
                            System.err.println(e.getMessage());
                    }
            }
    }
    

    DataDao.java

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    
    public class DataDao {
        private Connection connection;
    
        public DataDao() throws Exception {
            connection = DBUtility.getConnection();
        }
    
        public ArrayList<String> getFrameWork(String frameWork) {
            ArrayList<String> list = new ArrayList<String>();
            PreparedStatement ps = null;
            String data;
            try {
                ps = connection
                        .prepareStatement("SELECT * FROM marketing_database.lead  WHERE Company_Name  LIKE ?");
                ps.setString(1, frameWork + "%");
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    data = rs.getString("Company_Name");
                    list.add(data);
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            return list;
        }
    }
    

    DBUtility.java

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DBUtility {
        private static Connection connection = null;
    
        public static Connection getConnection() throws Exception {
            if (connection != null)
                return connection;
            else {
                // Store the database URL in a string
    
                Class.forName("com.mysql.jdbc.Driver");
    
                // set the url, username and password for the databse
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database","root","root");
                return connection;
            }
        }
    }
    

    web.xml

    <welcome-file-list>
       <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
      <servlet-name>SearchController</servlet-name>
    <servlet-class>com.servlet.Controller</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>SearchController</servlet-name>
      <url-pattern>/SearchController</url-pattern>
    </servlet-mapping>
    
  • FIFA oneterahertz
    FIFA oneterahertz about 8 years
    Thank You.Another question. Can we store the name selected in a variable and pass it to another page
  • Vinoth Krishnan
    Vinoth Krishnan about 8 years
    Welcome..Yes you can do. Store it in any hidden element(say textbox) and pass the value.