daydreamer
daydreamer

Reputation: 91959

jQuery: setting up CSRF token for Django not working

my jQuery function looks like

$(function() {
    // activate "New" buttons if input is not empty
    $('form input[type="text"]').live('keyup', function() {
        var val = $.trim(this.value);
        $(this).next("button").prop('disabled', val.length === 0);
    });

    $("body").on("submit","form",function(e){
        // do not submit the form
        e.preventDefault();

        // handle everything yourself
        var $form = $(this);
        var title = $form.closest('.video-detail').find('.title').text();
        var entryTitle = $form.find('.input-small').val();
        console.debug(title);
        console.debug(entryTitle);  

        $.ajaxSetup({ 
             beforeSend: function(xhr, settings) {
                 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;
                 }
                 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                     // Only send the token to relative URLs i.e. locally.
                     xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                 }
             } 
        }); 

        // send the data to the server using .ajax() or .post()
        $.ajax({
            type: 'POST',
            url: 'addVideo',
            data: {
                video_title: title,
                csrfmiddlewaretoken: '{{ csrf_token }}'
                },
        }).done(function(){
            alert('done');
        });
    });
});

This is based on answer Django CSRF check failing with an Ajax POST request

My html looks like

<form class="new-playlist form-inline" onclick="event.stopPropagation()">{% csrf_token %}
    <input type="text" class="input-small">
    <button class="btn btn-danger create-playlist-button" type="submit" disabled="disabled">New</button>
</form>

When I debug the code in Firefox, I see post values as

csrfmiddlewaretoken {{ csrf_token }}
video_title The Who - Who Are You?

How can I populate the {{ csrf_token }} value?

Thank you

Upvotes: 2

Views: 5145

Answers (2)

scrat.squirrel
scrat.squirrel

Reputation: 3826

In my case I have a template in which I don't want to have a <form></form> element. But I still want to make AJAX POST requests using jQuery.

I got 403 errors, due to CSRF cookie being null, even if I followed the django docs (https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/). The solution is in the same page, mentioning the ensure_csrf_cookie decorator.

My CSRF cookie did get set when I added this at the top of my views.py:

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie

Also, please note that in this case you do not need the DOM element in your markup / template: {% csrf_token %}

Upvotes: 9

edhedges
edhedges

Reputation: 2718

<input type="hidden" name="csrfmiddlewaretoken" value="SOME_TOKEN">

Above is the markup outputted by django. You want to grab the value of SOME_TOKEN. You will not be able to get it using the django template engine mixed with javascript since it will already be rendered into the input hidden.

I would wrap my {{ csrf_token }} in a span/div and then use jquery to locate that span/div and grab the value of the input inside the span/div.

Upvotes: 0

Related Questions