0

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

1
  • Is it that you are creating a complete form in javascript and appending it to your template somewhere? Commented Jun 17, 2016 at 4:08

2 Answers 2

3

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(),
Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

You are the first person i see using 8 space indention
@Endless It is wired. I have no idea why 8. I will figure out why.
@Endless Thanks. I did something wrong when copy and paste. and on my new VM, I did not set .vimrc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.