I am trying to implement the jQuery autocomplete plugin by receiving the data through a servlet.
The script works and it does pull the results from the servlet but I can’t get it to render properly in the drop down menu. Say I write “hel” in the search bar, the autocomplete drop down list is:
h
e
l
l
o
From what I understand, the autocomplete plugin is supposed to receive an array and I think that may be the issue.
This is my javascript code:
<script>
function getFilteredNames(request, response){
$.ajax({
type: "POST",
url: "../servlet/Autocomplete",
data: request,
success: function(data) {
response(data);
}
});
}
$(document).ready(function(){
$("#buscar").autocomplete({ source : getFilteredNames, minLength: 3});
});
</script>
And this is part of the servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String query = request.getParameter("term");
List<Socio> rs = new ArrayList<Socio>();
rs = SocioDAO.getSociosByQuery(query);
if (rs.isEmpty()) {
out.println("No hay coincidencias");
}
else {
Iterator <Socio> iterator = rs.iterator();
while (iterator.hasNext()) {
String nombre = (String) iterator.next().getNombre();
out.println(nombre);
}
}
Any suggestions would be greatly appreciated!
Thanks,
Nick
The autocomplete UI plugin accepts array,object formatted in JSON data.
sending to client side through ajax call.
for converting ur data to json format u can use utility call provided by http://www.json.org/