I'm trying to incorporate a simple AJAX function with Django and I've no idea what I'm doing wrong. request.is_ajax()
is returning False
and even when I do event.preventDefault()
, the form is still being submitted.
Here is the view:
def search(request):
if request.is_ajax():
search_text = request.POST.get('search_text', False)
else:
search_text = 'Not AJAX'
return HttpResponse(search_text)
The JS:
$(function(){
$('#search_form').submit(function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: {% url 'users:search' %},
dataType: 'html',
data: {
'search_text': $('#search').val(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(data){
$('#search-results').html(data);
},
failure: function(data){
alert('Got an error');
}
});
return false;
});
});
And the HTML:
<div class="col-md-4">
<h5>Search</h5>
<form action="{% url 'users:search' %}" method="POST" id="search_form" name="search_form">
{% csrf_token %}
<input type="text" id="search" name="search">
<input type="submit" value="Search">
</form>
<ul id="search-results">
{% if users %}
{% for user in users %}
<li><a href="{% url 'users:detail' user.id %}">{{ user.username }}</a></li>
{% endfor %}
{% else %}
<p>No user available</p>
{% endif %}
</ul>
</div>