[Answer]-Django Ajax search will not work

1👍

You are only fetching Data, there is no reason to use POST, just use GET.

$(function (){

    $('#search').keyup(function(){

        $.ajax({
            type: 'GET',
            url: '/main/search/',
            data: {search_text:$('#search').val()},
            success: function(newData) {
                $('#search-results').html(newData);
            }
        });

    });

});

EDIT: you filter on approved in your question, yet I see no approved field in your model. I have removed approved from the filtering in the bellow view to follow your model
Refactored your view, no need for so many lines of code.

def search(request):

    documents = None

    """
    request.GET.get will always return the value of the key if set or None (you can alternatively specify a default return value).
    """
    search_text = request.GET.get('search_text')

    if search_text :
        """
        Use some try, catch we don't need the server to fail because of a search action...
        """
        try:
            documents = Document.objects.filter(document_subject__contains=search_text)
        except:
            pass

    return render(request, 'ajax_search_html',{'documents':documents})

In the view you could add: if request.is_ajax() to check if this is an ajax request, but since your view feels acting the same ajax or not I see no reason.

The template:

{% if documents %}
    {% for document in documents %}
        <li><a href="/main/get/{{ document.id }}/">{{ document.document_subject }}</a></li>
    {% endfor %}

 {% else %}
    <li> None to show!!</li>
 {% endif %}

Leave a comment