N
N
nurzhannogerbek2017-04-18 15:23:11
JavaScript
nurzhannogerbek, 2017-04-18 15:23:11

“CSRF token missing or incorrect” in AJAX / Django?

Hello! How to fix this problem?

There is a page where a list of tasks is displayed and under each task there is a form for adding a comment. I'm using AJAX to add a new task and update the list of tasks. A new task is added and the list is updated, but then, when I try to add a comment to the form and send a new comment, an error is displayed , which you can see in the picture below

7c2a98d11cbf4a61993671b9b4c4a9b4.PNG

: Site Request Forgery protection . I just don't understand how to screw it on. Please help me solve this problem.

JS:

$(function () {
    var loadForm = function () {
        var btn = $(this);
        $.ajax({
            url: btn.attr("data-url"),
            type: 'get',
            dataType: 'json',
            beforeSend: function () {
                $("#modal").modal("show");
            },
            success: function (data) {
                $("#modal .modal-content").html(data.html_task_form);
            }
        });
    };

    var saveForm = function () {
        var form = $(this);
        $.ajax({
            url: form.attr("action"),
            data: form.serialize(),
            type: form.attr("method"),
            dataType: 'json',
            success: function (data) {
                if (data.form_is_valid) {
                    $("#task-list").html(data.html_task);
                    $("#modal").modal("hide");
                }
                else {
                    $("#modal .modal-content").html(data.html_task_form);
                }
            }
        });
        return false;
    };
    // Create Task
    $("#task-add-button").click(loadForm);
    $("#modal").on("submit", ".js-task-add-form", saveForm);
    // Update Task
    $("#task-list").on("click", "#js-edit-task-button", loadForm);
    $("#modal").on("submit", ".js-task-edit-form", saveForm);
});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nekr0z, 2017-04-18
@Nekr0z

To "pass CSRF to AJAX", you need to make an AJAX request with the parameter:

data: {csrfmiddlewaretoken: getCookie('csrftoken')}

The function getCookie()is described on that documentation page that you found.

Y
Yuri Moroz, 2017-04-18
@OPT_DEEP

You need to add a hidden input to the form with a csrf token. More or less like this:

<form method="post">
                        {% csrf_token %}
                        {% for field in form %}
                                {{ field.errors }}
                                {{ field.label_tag }}
                                {{ field }}
                        {% endfor %}
                        <button type="submit"Submit</button>
                    </form>

You can send it like this:
var saveForm = function () {
        var form = $(this);
        var formData = new FormData(this);
        $.ajax({
            url: form.attr("action"),
            data: formData,
            contentType: false,
            processData: false,
            type: form.attr("method"),
            success: function (data) {
                if (data.form_is_valid) {
                    $("#task-list").html(data.html_task);
                    $("#modal").modal("hide");
                }
                else {
                    $("#modal .modal-content").html(data.html_task_form);
                }
            }
        });
        return false;
    };

J
JonGalt, 2017-04-21
@JonGalt

It works like this for me:
I made myself a universal function for post requests via ajax:

function ajax_post(url, form_id, block_id) {
            var form = $(form_id).serialize();
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: form,
                    dataType: 'html',
                    success: function (data) {
                        $(block_id).html(data);
                    }
                });
                return false;
        }

and then just refer to it in the forms
<form action="javascript:void(null);" onsubmit="ajax_post('{% url 'companies' project %}', '#project_company_form', 
       '#content')" id="project_company_form">
      {% csrf_token %}
         {{ form.company }}
      ....
         <button type="submit"> Add </button>
   </form>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question