I'm trying to have a live search feature where as soon as you type something in a search box, the results automatically appear right below. I've been following this tutorial with no luck. Nothing seems to be happening when I type a query.
Could anybody tell me what I'm doing wrong?
urls.py
urlpatterns = [
url(r'^$', views.list_of_post, name='list_of_post'),
[...]
url(r'^search/$', views.search_titles),
]
# this is my blog app views. Original view contains
# url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
views.py
# Main view that displays all my posts
def list_of_post(request):
post = Post.objects.filter(status='published')
categories = Category.objects.all()
template = 'blog/post/list_of_post.html'
context = {
'posts': posts,
'categories': categories,
[...]
}
return render(request, template, context)
# View that should return my results?
def search_titles(request):
if request.method == 'POST':
search_text = request.POST['search_text']
else:
search_text = ''
classes = Post.objects.filter(title__contains=search_text)
return render_to_response('blog/ajax_search.html', {'classes': classes})
template
<h3>Search</h3>
{% csrf_token %}
<input type="text" id="search" name="search"/>
<ul id="search-results">
</ul>
ajax_search.html
{% if classes %}
{% for class in classes %}
<p>{{ class.title }}</p>
{% endfor %}
{% else %}
<p>No classes found.</p>
{% endif %}
and finally, ajax.js
$(function() {
$('#search').keyup(function() {
$.ajax({
type: "POST",
url: "blog/search/",
data: {
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data)
}
all my files are loaded up properly, a quick console check confirms ajax.js & jquery being loaded with no errors. When I type anything in my search box, nothing appears below. I have followed the tutorial pretty consistently and I can't see where I might have gone wrong. If anybody could help, it would be appreciated!