GrantU
GrantU

Reputation: 6555

CSRF token missing or incorrect using Jquery

I have the following code below but I still get "CSRF token missing or incorrect." error. anyone spot what I have done wrong here?

<form method="post" action="" id="registration">
  {{ form.as_p }}

  <input type="submit" value="{% trans 'Submit' %}" />
</form>


 <script>

$('#registration').submit(function(e){
     e.preventDefault(); //prevent default form submit

   $.ajax({

       url: '/accounts/registerAjax/',
       type: 'POST',
       contentType: "application/json;charset=utf-8",
       dataType: "json",
       data: {
             'csrfmiddlewaretoken': '{{ csrf_token }}',
            'id_username': $("#id_username").val(),
            'id_email': $("#id_email").val()
            },
        success: function() {
            alert('Test');

        },
        error: function(errorThrown){
            console.log(errorThrown);
            alert('Error');
            alert(errorThrown);
        }
    });

Upvotes: 0

Views: 744

Answers (1)

Ewan
Ewan

Reputation: 15058

From the docs.

on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token.

As a first step, you must get the CSRF token itself. The recommended source for the token is the csrftoken cookie, which will be set if you’ve enabled CSRF protection for your views as outlined above.

// 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');

The above code could be simplified by using the jQuery cookie plugin to replace getCookie:

var csrftoken = $.cookie('csrftoken');

Upvotes: 2

Related Questions