Reputation: 89
I want to implement autocomplete functionality on my web page using django. I went ahead with jquery autocomplete which has sufficient documentation on how to achieve it. I have made changes accordingly to my django views and urls as well. Still I am not able to view any entries in autocomplete.
Below are code fragments which would give a clear idea of how i implemented it
mypage.html
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
...
...
<script>
$(function() {
var entries= [
"emp1",
"emp2",
"emp3",
"emp4",
"emp5"
];
$("#vote").autocomplete({
source: "api/get_employees/",
});
});
</script>
...
...
...
<div class="ui-widget">
<input id="vote" type="text" name="vote"/>
<input type="submit" value="Vote" />
</div>
urls.py
url(r'^api/get_employees/', views.get_employees, name='get_employees')
views.py
def get_employees(request):
data = ['MyName']
return HttpResponse(json.dumps(data),'application/json')
I have tried passing [{id:'MyName'}] to data as well. But still I dont get it during autocomplete. I am sure nothing is wrong with the jquery part because if i pass entries variable to source, everything works fine. Only when i change it to get data from the django view, it runs into issues. Any pointers in this regard would be helpful. I have tried other posts in stackoverflow but to no avail.
Upvotes: 1
Views: 2527
Reputation: 89
First of all thanks to all the answers. They helped me form the correct json to pass back. But then i found out that I missed a line "import json". Everything was working fine even without this line which i am clueless about. Again any pointers appreciated.
After doing the import and passing correct json back, I am able to see the list of entries with autocomplete.
Upvotes: 0
Reputation: 370
The Autocomplete documentation is not very clear. To make it work, you will need to ensure that api/get_employees?term=...
will return a JSON array structured like so:
[ {"value":"3","label":"Matching employee A"},
{"value":"5","label":"Matching employee B"},
etc.
]
Upvotes: 1
Reputation: 859
Your JSON should look like this:
[
{
"id":"Ficedula hypoleuca",
"label":"Eurasian Pied Flycatcher",
"value":"Eurasian Pied Flycatcher"
},
{
"id":"Muscicapa striata",
"label":"Spotted Flycatcher",
"value":"Spotted Flycatcher"
}
]
When you look at the example at http://jqueryui.com/autocomplete/#multiple-remote you can see that the autocomplete is 'asking' http://jqueryui.com/resources/demos/autocomplete/search.php
You should also use /api/get_employees/
instead of api/get_employees/
Maybe this is also importend(for your django-part): jquery uses the parameter term to for the searchword. For example http://jqueryui.com/resources/demos/autocomplete/search.php?term=ca is searching for 'ca'
Upvotes: 2