CodeFanatic23
CodeFanatic23

Reputation: 89

Display Search results of django ajax search

I have been following a tutorial on django-ajax search.I cannot get to display the results in the templates though they "print" just fine in terminal.How do i get these results on the html page? here's my views.py:

def search_titles(request):
    if request.method == 'POST':
        search_text = request.POST['search_text']
        print search_text
        search = UploadFile.objects.filter(event_name__icontains=search_text)
        for i in search:
            print(i.event_name)

        context={
        'search':search,
        }

        return render(request,'ajax_search.html',context)

HTML Template:

<!DOCTYPE html>
<html>
<head>
    <title>Search</title>

    <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.min.js"></script>
    <script type="text/javascript" src="/static/assets/js/ajax.js"></script>
</head>
<body>
<h3>Search</h3>
                {% csrf_token %}
                <input type ='text' id="search" name="search"/>
                <ul id="search-results">

                </ul>



</body>
</html>

ajax.js:

$(function(){

    $('#search').keyup(function(){
    $.ajax({
      type:"POST",
      url:"/search",
      data:{
        'search_text': $('#search').val(),
        'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
      },
      success: searchSuccess,
      dataType: 'html'
    });
  });
});

function searchSuccess(data, textStatus,jqXHR)
{
  $('#search-results').html(data);
}

ajax_search.html:

{% if search.count>0 %}

{% for i in search %}

<li><a href="events/{{i.event_name}}">{{i.event_name}}</a></li>
{% endfor %}

{% else %}
<li>Nothing Found :(</li>

{% endif %}

urls.py:

......
url(r'^events', event_list),#renders search.html
url(r'^search',search_titles),#renders ajax_search.html
......

Django Ajax search will not work thread seems to have similar issue..but following this doesn't even give search results in terminal.

Upvotes: 1

Views: 1546

Answers (1)

Anoop
Anoop

Reputation: 2808

You should use HttpResponse to return response to an ajax request. And if you are using Django 1.7+ then use JsonResponse

from django.template.loader import render_to_string
from django.http import HttpResponse

def search_titles(request):
    context ={}
    if request.method == 'POST':
        search_text = request.POST['search_text']
        search = UploadFile.objects.filter(
                     event_name__icontains=search_text)   
        context={
        'search':search,
        }
        html = render_to_string('search_results.html',context)

        return HttpResponse(html, content_type="application/json")    
    return render(request,'ajax_search.html',context)

Create a new html

search_results.html:

{% for i in search %}<li>{{i.event_name}}</li>{% endfor %}

Upvotes: 1

Related Questions