in template:
<script type="text/javascript">
$.ajax({
type:"POST",
url:"{% url DrHub.views.ajxTest %}",
data: {
'start': $('#id_startTime').val(),
'end': $('#id_endTime').val(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(data){
alert(data);
}
});
</script>
.
.
.
<form method='POST' action=".">
{% csrf_token %}
<input type="text id="id_startTime" />
<input type="text id="id_endTime" />
<input type="submit" value="send" />
</form>
in views:
def ajxTest(request):
if request.is_ajax():
if request.method == 'POST':
return HttpResponse(json.dumps({'message' : 'awesome'},ensure_ascii=False), mimetype='application/javascript')
in settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
when submitting form I have this error:CSRF verification failed. Request aborted.
I searched alot but none of suggested solutions worked for me!
like : Django CSRF check failing with an Ajax POST request
and : Ajax Post in Django framework?
I refreenced to a js file with this content:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
but this didn't work,too!
And I saw a solution that say use ajaxSetup instead of ajaxSend to post data,how can I do this?