This question is not new, however I've spent really plenty of time, but coudn't fixed it.
<form id="test_data_form" action={% url 'insert_test_data' %} method="post">{% csrf_token %}
<input type="submit" value="Insert test data">
<div id="message"></div>
</form>
<script type="text/javascript">
var form = $("test_data_form");
$(document).ready(function() {
form.submit(function() {
$.ajax({
data: form.serialize(),
url: form.attr('action'),
cache: false,
type: form.attr('method'),
dataType:'json',
success: function(response) {
alert("1");
},
error: function() {
alert('Error!');
}
}
);
return false;
}
);
}
);
</script>
views.py
@csrf_exempt
def insert_test_data(request):
print request.is_ajax()
data = {'success': True, 'html': "text"}
return HttpResponse(json.dumps(data), mimetype="application/json")
urls.py
url(r'^hello/insert_test_data/$', insert_test_data, name="insert_test_data"),
Firstly, I've found that success isn't caught, so then while debugging I found that django doesn't think it is an ajax request and redirects me to the different page: /insert_test_data. And I want to stay on the home page.
I've found a lot of advices about that problem (e.g. cache: false) but none of them helped. I agree, that I miss something obvious, but couldn't figure out what exactly. I'll be realy glad for any help.