Reputation: 8946
I am using the answer here (JavaScript post request like a form submit) to do post in my javascript at the brower. But Django CSRF checking failed because there is {% csrf_token %} in the form in the template. How to do it? Should I add the following piece of codes?
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", 'csrfmiddlewaretoken');
hiddenField.setAttribute("value", '{{ csrf_token }}');
form.appendChild(hiddenField);
Any hints, suggestions and comments welcomed. Thanks
Upvotes: 0
Views: 839
Reputation: 430
If you are submitting form using ajax you also have to submit csrf token value. For an example.
$.ajax({
type: "POST",
url: url,
data:{
'csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val(),
},
success: function(response){
}
});
or you can send serialize form in ajax data as
data: $("#form").serialize(),
Upvotes: 3
Reputation: 8946
I used the getCookie() function from https://github.com/sigurdga/django-jquery-file-upload/blob/master/fileupload/static/js/csrf.js and post() function from JavaScript post request like a form submit.
Final codes:
// https://github.com/sigurdga/django-jquery-file-upload/blob/master/fileupload/static/js/csrf.js
function getCookie(name) {
console.log('getCookie');
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;
}
}
}
console.log('cookie:' + cookieValue);
return cookieValue;
}
// https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
var hiddenField1 = document.createElement("input");
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("name", 'csrfmiddlewaretoken');
hiddenField1.setAttribute("value", getCookie('csrftoken'));
form.appendChild(hiddenField1);
document.body.appendChild(form);
form.submit();
}
Any comments welcomed.
Upvotes: 0