Jquery ajax loads a list of results, even there nothing is requested

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}) 
0
source share
1 answer
 $('#search').keyup(function () { if (!$.trim(this.value).length) return; //<< returns from here if nothing to search $.ajax({ type: "POST", url: "/status/search_status/", data: { 'search_text': $('#search').val(), 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); 

By the way, you should activate your request on the keyboard to avoid multiple calls if the user types too quickly:

 (function () { var throttleTimer; $('#search').keyup(function () { clearTimeout(throttleTimer); throttleTimer = setTimeout(function () { if (!$.trim(this.value).length) return; $.ajax({ type: "POST", url: "/status/search_status/", data: { 'search_text': $('#search').val(), 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }, 100); }); }()); 
+1
source

Source: https://habr.com/ru/post/1501679/


All Articles