Robin
Robin

Reputation: 5486

jquery ajax loads list of results even there's nothing to query

So I am learning from a tutorial for jquery and ajax and till now I have a search form for searching and returning the search results. And it works fine. But when I delete the words from the form or backspace the words, it loads all the status in the list. What do I do to return only when there is some word and to return nothing if there's no word in the form.

snippet of status.html:

{% 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})

Upvotes: 0

Views: 447

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

$('#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'
    });
});

BTW, you should throttle your request on keyup to avoid multiple call if user is typing too fast:

(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);
    });
}());

Upvotes: 1

Related Questions