S
S
Sergey Nizhny Novgorod2016-07-19 05:11:45
Django
Sergey Nizhny Novgorod, 2016-07-19 05:11:45

How to pass csrf token to ajax django?

Hello.
Added to the form:
{% csrf_token %}
Made a script:

<script>
    $(".arsenal_vote_answer").click(function(e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: '/arsenal_votedone{{ arsenalitem.id }}',
            data:{
                arsenal: $('.arsenal_label').val(),
                csrfmiddlewaretoke: $('input[name=csrfmiddlewaretoke]').val(),
            },
            success: function(data){

                if (data) {
                    $('.arsenal_vote_figure').html(data.ars1)
                    $('.arsenal_vote_figure1').html(data.ars2)
                    $('.arsenal_vote_figure2').html(data.ars3)
                }
                else
                {}
            }
        });
    });

</script>

When I click the button, I get an error 403 - Failed to load resource: the server responded with a status of 403 (Forbidden)
The description of the error shows that the csrf token is being abused.
If you just process the form, then everything goes, it swears at ajax. How to send a token in a request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shuvalov_aa, 2020-07-24
@shuvalov_aa

Try to take the token not from the form input, but from the cookie

var a = document.cookie.split(';');
var token = ''
for (i = 0; i < a.length; i++) {
    var b = a[i].split('=')
    b[0] = b[0].replace(/\s+/g, '')
    if (b[0] == 'csrftoken') {
        token = b[1]
    }
}

Substitute it in the request body later.
Well, then you have a typo in the name of the date key csrfmiddlewaretoken (missed at the end of n)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question