1

I want to make an autocomplete but not by using any java method. Just by using jsp, jquery, ajax and scriplets. Is it possible? Please suggest.

I tried using the code given below, but am getting error

Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method 'List.jsp'

The code is given below:

//(Index.jsp)

<html>
<head>

<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#country').focusin(function() {
$("#country").autocomplete("List.jsp");
});
});
</script>
</head>
<body>
    <br><br><center>
        <font face="verdana" size="2">
        <font size="4">Java(jsp)/jQuery Autocompleter Example</font>
        <br><br><br><br>

        Select Country   :
        <input type="text" id="country" name="country"/>

        </font>
    </body>
</html>

//(List.jsp)

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>

<%
    try {
        String s[] = null;

        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver found");
        String url = "jdbc:mysql://localhost:protNum/dbName";
        String user = "";
        String pass = "";
        System.out.println("Connected....");
        Connection con = (Connection) DriverManager.getConnection(url, user, pass);
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from tbctry");

        List li = new ArrayList();

        while (rs.next()) {
            li.add(rs.getString(1));
        }

        String[] str = new String[li.size()];
        Iterator it = li.iterator();

        int i = 0;
        while (it.hasNext()) {
            String p = (String) it.next();
            str[i] = p;
            i++;
        }

        //jQuery related start
        String query = (String) request.getParameter("q");

        int cnt = 1;
        for (int j = 0; j < str.length; j++) {
            if (str[j].toUpperCase().startsWith(query.toUpperCase())) {
                out.print(str[j] + "\n");
                if (cnt >= 5)// 5=How many results have to show while we are typing(auto suggestions)
                {
                    break;
                }
                cnt++;
            }
        }
 //jQuery related end

        rs.close();
        st.close();
        con.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
%>

I want the textbox to autopopulate values from database on keydown. I have done this using spring MVC, but I'm not getting any clue how to do this without using any java class but by just using jsp, jquery, ajax, and scriplets. Please help!

Arahan Jha
  • 13
  • 1
  • 8

2 Answers2

1

You can do that by using jquery onkeyup event ,when user start typing in input box the typed value will passed to your jquery function and by using ajax you can call your List.jsp page and get that value using request.getParameter("") ,lastly passed that value in your query and return result back using out.print like below :

Input i.e :where value will be typed :

    Select Country   :  <input type="text" id="country" name="country"/>
  //here result will be display
    <div id="result"></div>

Jquery & Ajax :

 <script>
     $('#country').keyup(function(){
       //getting typed value
            var searchid=$(this).val();
               if(searchid!='')
                     {
                        $.ajax({
                           type:"POST",
                            url:"List.jsp",
                            //passing value
                             data:{search:searchid},
                             success:function(html){
                            //response from List.jsp page will come here                                       
                                $('#result').html(html);
                            }
                         });
                         } 
                   });
        </script> 

List.jsp page :

//getting value passed from ajax
 String search = (String) request.getParameter("search");
//db setting
      try{
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver found");
        String url = "jdbc:mysql://localhost:protNum/dbName";
        String user = "";
        String pass = "";
        System.out.println("Connected....");
        Connection con = (Connection) DriverManager.getConnection(url, user, pass);
          //below columnanme is fieldname from where you need to compare your search value.
        PreparedStatement pstmt = con.prepareStatement(
         "select * from tbctry where columnname LIKE ?");
         pstmt.setString(1, search + "%");
         ResultSet rs=pstmt.executeQuery();  
         while(rs.next()){ 
        //here you need to print values which you need to show in div 
         out.print("something"); 
          }
        rs.close();
    pstmt.close();
    con.close();

} catch (Exception e) {
    e.printStackTrace();
}

Hope this helps !

Swati
  • 28,069
  • 4
  • 21
  • 41
  • Thanks. Just one more help if possible, yes this code returns a list of output result. But i can't process them and bring the desired output. I have to look for something like JSON. I want to know How to make the List.jsp produce a JSON array which can be read back in ajax success. As its quite easy to process JSON data and also i can process to get the desired output. And also which variable of List.jsp is the success(response) mapping to? As when the code gets executed, response has the data in it but from which variable of List .jsp it is getting the data? – Arahan Jha Jun 03 '19 at 08:48
  • I tried the following code but am unable to read a JSON format data in response. while(rs.next()) { item = new JSONObject(); item.put("building", rs.getString(2)); item.put("floor", rs.getString(3)); dataArray.put(item); } – Arahan Jha Jun 03 '19 at 08:58
  • Have a look [here](https://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax) for good example , also whatever `out.println()` has will return back has response. – Swati Jun 03 '19 at 11:34
  • Thanks, I used JSONArray and JSONObject to solve my issue. Also I used autocomplete to populate the options. Complete code I am providing in the answer. Thanks a lot as you provided me the initial guide to resolve my issue. And also your link in your 2nd comment was an excellent reference, Thanks! – Arahan Jha Jun 05 '19 at 07:44
0

List.jsp Page

<%@page import="java.util.*" %>
<%@page contentType="text/html; charset=UTF-8"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.parser.JSONParser"%>
<%@page import="org.json.simple.parser.ParseException"%>
<%@ include file = "connect.jsp"%>

<%

//getting value passed from ajax
 String search = (String) request.getParameter("search");
    try{
        JSONArray dataArray = new JSONArray();
        JSONObject item = null;
        PreparedStatement pstmt = con.prepareStatement("select * from LPRONE.POINFO where PONO LIKE ?");
         pstmt.setString(1, search + "%");
         ResultSet rs=pstmt.executeQuery();  
         while(rs.next()){ 
            item = new JSONObject();
            item.put("name", rs.getString(12));
            dataArray.add(item);
          }
        //here you need to print values which you need to show in div
        out.println(dataArray); 
    } catch (Exception e) {
        e.printStackTrace();
    }

%>

I've used JSONObject and JSONArray to get the resultset and passed it over to the calling jsp page through out.ptintln().

Input.jsp Page

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <script src="jquery/jquery-1.7.min.js"></script>
    <script src="jquery/jquery.autocomplete.min.js"></script>
        <script src="jquery/jquery-ui.js"></script>
        <title>JSP Page</title>
    </head>
    <body>
<div class="form-group">
  Select Country   :  <input list="newlist" type="text" id="PO" name="PO"/>
  //here result will be display
    <datalist id="newlist"></datalist>
</div>

  <script>
     $('#PO').keyup(function(){
       //getting typed value
            var searchid=$(this).val();
               if(searchid!='')
                     {
             $(function(){
             $("#PO").autocomplete({
             source:function(request, response){
                        $.ajax({
                           type:"get",
                            url:"List.jsp",
                            //passing value
                             data:{search:searchid},
                             success:function(response){
                            //response from List.jsp page will come here     
                var obj = JSON.parse(response);
                if(!obj){

                }
                else{
                var dl = document.getElementById("newlist");
                dl.innerHTML="";
                for(var i=0; i<obj.length; i++)
                {
                var opt=document.createElement('option');
                dl.appendChild(opt);
                opt.innerHTML = opt.innerHTML + obj[i].name;
                }

                }
                            }
                         });
             }
             });
             });
                         } 
                   });
        </script> 

    </body>
</html>

Here I've binded the values in success of ajax call. This is working example of autocomplete with the use of jsp, jquery, ajax, scriplets, JSON and autocomplete function. No servlets used.

Arahan Jha
  • 13
  • 1
  • 8