Answer the question
In order to leave comments, you need to log in
Django csrf. Ajax feedback form. How to send?
Good day!
Send ajax request button:
<button type="submit" class="btn btn-primary" onclick=save_feedback("{% url 'save_feedback'%}","test","test")>Submit</button>
url(r'^feedback/', views.save_feedback, name='save_feedback'),
function save_feedback(url, email, message) {
$.ajax({
url: url,
type: "POST",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'email': email,
'message': message
}
});
}
def save_feedback(request):
print("debug")
return render(request, 'base/feedback.html')
Forbidden (CSRF token missing or incorrect.): /feedback/
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;
}
Answer the question
In order to leave comments, you need to log in
https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
</head>
<body>
<form action="{% url form_url %}" class="js-feedback_form" method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Foo</button>
</form>
<script>
// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
var $feedback_form = $('.js-feedback_form');
$feedback_form.submit(function (e) {
e.preventDefault();
$.ajax({
method: 'post',
url: $feedback_form.attr('action'),
data: $feedback_form.serialize(),
success: function(data) {
alert('Data send');
}
});
})
</script>
</body>
</html>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question