So, I am studying a tutorial for jquery and ajax, and so far I have a search form for searching and returning search results. And it works great. But when I remove the words from the form or backspace of the word, it loads all the status in the list. What should I do to return only when there is some word and nothing to return if there is no word in the form.
fragment of the status.html file:
{% block add_account %} <input type="text" id="search" name="search" /> <ul id="search-results"> </ul> {% endblock %}
ajax.js:
$(function() { $('#search').keyup(function() { $.ajax({ type: "POST", url: "/status/search_status/", data: { 'search_text' : $('#search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data) }
ajax.html:
{% if statuss.count > 0 %} {% for status in statuss %} <li><a href="/status/get/{{status.id}}/">{{status.status}}</a></li> {% endfor %} {% else %} <p>None to show</p> {% endif %}
views.py
def search_status(request): if request.method == "POST": search_text = request.POST['search_text'] else: search_text='' statuss = Status.objects.filter(status__icontains = search_text) return render(request, 'ajax_search.html', {'statuss':statuss})
source share