Django ajax jQuery autocomplete only works on one page

I've added a working search field to a navigation bar that use jQuery autocomplete. The problem is it only works on the main page. On the other pages it tries to add the source url to the end of the page url.

For instance, on the home page it points to ajax_call/search, but on a company page (it's app that gathers internal data on companies) it points to company/847/ajax_call/search and obviously fails.

What do I need to do so the jQuery autocomplete functionality works across the entire site (without rewriting it in every template)?

Template

$(function() {
    $("#tags").autocomplete({
        minLength:2,
        source: "ajax_call/search/",
        select: function(event, ui){
            window.location.href = ui.item.href;
        }
    });
});

URL

url(r'^ajax_call/search/$', views.ajax_company_search, name='search-field'),

View

def ajax_company_search(request):
    if request.is_ajax():
        query = request.GET.get('term', '')
        company_names = Company.objects.filter(company_name__icontains=query).values('company_name', 'pk')

        results = []
        for name in company_names:
            name_json = dict()
            name_json['label'] = name['company_name']
            name_json['value'] = name['company_name']
            name_json['href'] = "company/" + str(name['pk']) + "/"

            results.append(name_json)

        data = json.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
return HttpResponse(data, mimetype)

1 answer

  • answered 2017-11-14 23:56 Sören Weber

    You specified a relative URL in your JavaScript function. That's why it changes when you visit another page (with a different URL). In this case you want to use an absolute URL, like this: /ajax_call/search/.

    Also, it is best practice to not hard-code your URLs in templates but to use reverse resolution:

    $(function() {
        $("#tags").autocomplete({
            minLength:2,
            source: {% url 'search-field' %},
            select: function(event, ui){
                window.location.href = ui.item.href;
            }
        });
    });