Skip to content

Instantly share code, notes, and snippets.

@mitchdowney
Created October 7, 2013 00:43
Show Gist options
  • Save mitchdowney/6860996 to your computer and use it in GitHub Desktop.
Save mitchdowney/6860996 to your computer and use it in GitHub Desktop.
Now when I type anything into the typeahead box, the dropdown with query results appears and says "undefined"
When I visit the following URL http://127.0.0.1:8000/lookup/universities/?query=K
The page displays the following text:
{"options": ["Kenny University", "Kent State"]}
<form method="post">{% csrf_token %}
<label>My Label</label>
<input type="text" data-provide="typeahead" class="searchAhead" name="i1" />
<input type="submit" value="submit" class="button" />
</form>
<script type="text/javascript">
$('.searchAhead').typeahead({
name: 'Search',
remote: '/lookup/universities/?query=%QUERY'
});
</script>
from everyvote_mini.models import ParentConstituency
from django.http import HttpResponse
from django.utils.html import escape
from django.utils import simplejson
# TYPEAHEAD PARENT CONSTITUENCY
def typeahead(request, search_type):
resultSet = {}
if search_type == 'universities':
if request.method == "GET":
if request.GET.has_key(u'query'):
query = request.GET[u'query']
obj = ParentConstituency.objects.filter(name__contains=query)
results = [ escape(x.name) for x in obj ]
resultSet["options"] = results
return HttpResponse(simplejson.dumps(resultSet), content_type="application/json")
# TYPEAHEAD
url(r'^lookup/(?P<search_type>\w+)/$', 'everyvote_mini.views.typeahead.typeahead', name='typeahead'),
@mitchdowney
Copy link
Author

I changed typeahead.py to this:

def typeahead(request, search_type):
    resultSet = {}
    if search_type == 'universities':
        if request.method == "GET":
            if request.GET.has_key(u'query'):
                query = request.GET[u'query']
                obj = ParentConstituency.objects.filter(name__contains=query)
                results = [ escape(x.name) for x in obj ]
                resultSet["options"] = results
        json = simplejson.dumps(results)
    return HttpResponse(json, mimetype="application/json")

And now when I visit http://127.0.0.1:8000/lookup/universities/?query=K

It displays:

["Kenny University", "Kent State"]

Which is apparently the proper json I need, because now the typeahead is working properly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment