[Answered ]-CSRF With Ajax Polling

2πŸ‘

βœ…

The solution to this problem is described in the Django documentation: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

Add this code to the top of your js:

$.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'));
        }
    }
});
πŸ‘€GreyZmeem

0πŸ‘

You need to pass csrf token along with your post data:

var date = $('article').first().find('time').text();
console.log(date);

setInterval(function() {
    $.post('pollNewEntries', {'date':date, 'csrfmiddlewaretoken': '{{csrf_token}}'}, newEntrySuccess)
}, 5000);
πŸ‘€Aamir Rind

0πŸ‘

Simply add these lines in your script. Here is an example in coffeescript :

### CSRF methods ###
csrfSafeMethod = (method) ->
  # these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method))

$.ajaxSetup(
  crossDomain: false
  beforeSend: (xhr, settings) ->
    if !csrfSafeMethod(settings.type)
      xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'))
)

Read the documentation : CSRF

In other hand, as user1427661 suggests to you, it will be better to use HTTP GET method instead of POST, because you only need to read data and don’t write anything. See the W3 docs.

πŸ‘€rphonika

Leave a comment