Question

I've been trying to get this to work for a couple of days now and I'm not getting anything with the code I have. I have a form that has a textbox that needs to list outside salesmen that I am trying to use autocomplete.

This is the code for the form (doorform2.jsp)

<script>
    $("#outsideSales").autocomplete({source: "outsideIn.jsp",minLength: 2});
</script>

<input type="text" name="outsideSalesman" id="outsideSales" required>

This is the code that I am using to get data from my database to use for the autocomplete

<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://nemesis:1433;instanceName=gfi;databaseName=NationalFormsRepository;user=portal;password=P0rtal");
stmt = con.createStatement();

String outside = request.getParameter("outsideSalesman");

ArrayList<String> outsideSalesmenNames = new ArrayList<String>();
String outsideSalesman = "SELECT outsideSalesName FROM tbl_outsideSales WHERE outsideSalesName like '%"+outside+"%'";

rs = stmt.executeQuery(outsideSalesman);

while(rs.next())
{
    outsideSalesmenNames.add(rs.getString("outsideSalesName"));
}
out.println(outsideSalesmenNames);

%>

I've tried to follow several tutorials online but most of the ones that I have been following are for php not jsp or they are for older versions of jquery autocomplete. I feel like I am missing something small but have been looking at it to long to see it. Can anyone take a look and see if I am missing anything?

Was it helpful?

Solution 2

First of all, your code is not wrapped inside $(document).ready(). The following will not work as expected:

<script>
$("#outsideSales").dosomething();
</script>
<!-- Note: #outsideSales does not exist before this line -->
<input id="outsideSales">

Revise your code like this:

<script>
$(document).ready(function(){
    $("#outsideSales").dosomething();
});
</script>
<input id="outsideSales">

#2: when you specify a URL as the source parameter, jQuery UI will send a request that contains the query string parameter term. So you need to modify your code accordingly:

String outside = request.getParameter("term");

#3: the jQuery UI expects a valid JSON instead of a string. So instead of this:

[Jack, Jill, John]

Your program needs to output:

["Jack", "Jill", "John"]

PS: your query is open to SQL injection.

OTHER TIPS

Your outsideIn.jsp must be return a JSON formated data.

From official docs: "The datasource is a server-side script which returns JSON data, specified via a simple URL for the source-option. In addition, the minLength-option is set to 2 to avoid queries that would return too many results and the select-event is used to display some feedback."

See here for more informations: link

Cheers :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top