ilyas Jumadurdyew
ilyas Jumadurdyew

Reputation: 930

How to get objects according to FK by using AJAX in django

I want to make a dropdown filter, which looks like this Auto Mark > Auto Model As you can understand the "Auto Model" list should change every time Auto Mark changes, because the data must change without refreshing page i have to use AJAX.

My views.py looks like

def search_models(request):
    args = {}
    args.update(csrf(request))
    if request.method == "POST":
        search_text = request.POST['search_text']
    else:
        search_text = ''
    args['models'] = AutoModel.objects.filter(mark_id__exact='search-text')
    args['val'] = search_text
    return render_to_response('ajax-main-filter.html', args)

And my ajax-search.js looks like:

$(function(){

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

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

    });

});

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

The problem is that variable 'search text' shows error or shows False value.

Please can someone help me...

Thank You

Upvotes: 1

Views: 69

Answers (1)

amureki
amureki

Reputation: 772

The reason is that your $('search').val() value is None, you should check why it could be.

Maybe its because you wrote wrong css selector and your selector should be

$('#search').val() 

instead of

$('search').val()

Upvotes: 1

Related Questions