<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;
}
<!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>