Trying to make a search/filter dropdown with select2 and ajax. my self defined is_ajax(request) function not working?
I am making a django project where there is a search/filter dropdown for a form. I am using select2 and ajax. It isn't working, and when I try to debug with print statements, it seems that the is_ajax(request) function is not returning true.
I know the is_ajax() function was deprecated in JQuery, which is why I defined it myself. However, mine doesn't seem to work either.
Here is the portion my view that filters objects:
@login_required
def job_application_create(request):
form = JobApplicationForm()
if is_ajax(request):
print('TESTING TESTING TESTING TESTING TESTING TESTING TESTING TESTING ')
term = request.GET.get('term')
companies = Company.objects.filter(name__icontains=term)
response_content = list(companies.values())
return JsonResponse(response_content, safe=False)
and here is the is_ajax(request) definition:
def is_ajax(request):
return request.headers.get('x-requested-with') == 'XMLHttpRequest'
Here is the JS in the page that has my form:
<script>
$(document).ready(function () {
$('#id_company').select2({
ajax: {
url: "{% url 'homepage' %}",
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {id: item.id, text: item.name};
})
};
}
},
minimumInputLength: 1
});
});
</script>