user6679565
user6679565

Reputation:

Django autocomplete - request.is_ajax() always returns false

New to Django. Trying to set up a page which has a text box that supports autocomplete. I referred to this post for guidance. For some reason, request.is_ajax() always returns false.

urls.py for the main app

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', home),
    url(r'^search_assist/', include('search_assist.urls')),
]

urls.py for the search_assist app

urlpatterns = [
    url(r'^$', views.search_assist, name='search_assist'),
]

views.py

def search_assist(request):
    if request.is_ajax():
        q = request.GET.get('term', '')
        states = State.objects.filter(state_name_full__icontains = q )[:20]
        results = []
        for state in states:
            state_json = {}
            state_json['id'] = state.id
            state_json['label'] = state.state_name_full
            state_json['value'] = state.state_name_full
            results.append(state_json)
        data = json.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

HTML

{% extends "gif_alpha_test/header.html" %}
  <div class="ui-widget">
      <label for="sassist">Search Assist: </label>
      <input type="text" id="sassist">
  </div>

header.html has the following jQuery function.

<script>
$( document ).ready(function() {
    assist();
});
function assist(){
            $.ajaxSetup({
                headers: {'X-Requested-With': 'XMLHttpRequest'}

            $("#sassist").autocomplete({
                source: "/search_assist/",
                minLength: 2,
            });});
        }
</script>

I have seen few other posts on a similar note but the comments / responses on those posts didn't help.

Any ideas on why request.is_ajax() always returns false? Appreciate the help.

Upvotes: 1

Views: 295

Answers (1)

itzMEonTV
itzMEonTV

Reputation: 20349

Add this on top of your JS call

$.ajaxSetup({
    headers: {'X-Requested-With': 'XMLHttpRequest'}
});

Upvotes: 0

Related Questions