Autocomplete-
Jquery Ajax Json Example in Java(using Servlet)
Here am using devbridge jquery api to achieve the
autocomplete functionality.
Requirements:
Eclipse
Mysql (or you can use any other database ,but in
lib folder you must add appropriate driver
for that database)
for that database)
To get country list
For Mysql
For Oracle
HTML Code
<input type="text" name="country"
id="autocomplete"
class="form-control"
placeholder="Enter Country name" />
Jquery Plugin to achieve Autocomplete from DevBridge
<script type="text/javascript"
src="src/jquery.autocomplete.js"></script>
Jquery Code
$("#autocomplete").autocomplete({
//lookup: countries,
serviceUrl:'Auto',
//tell the script where to send requests
width: 450, //set width
//callback just to
show it's working
onSelect:
function (suggestion) {
$('#selection').html('You
selected: ' + suggestion.value + ', ' + suggestion.data);
},
showNoSuggestionNotice:
true,
noSuggestionNotice:
'Sorry, no matching results',
});
Servlet Code
String
q=request.getParameter("query");
ArrayList<Country>
o=CountryDao.getCountryName(q);
Gson
gson = new Gson();
//
convert java object to JSON format,
//
and returned as JSON formatted string
String
json = gson.toJson(o);
//System.out.println(json);
response.getWriter().write("{\"suggestions\":"+json+"}");
Here the method is not mentioned so all the data will be
passed as GET method. If you want to pass the data through post mention in
Jquery like type:’POST’.
OUTPUT SCREEN