[Answer]-Csrf token issue with multiple templates

0๐Ÿ‘

โœ…

I finally made it work (based on django doc and doniyor comments)

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;
}

function Favorite(item) {
  song_id = item.getAttribute("data-mp3"),
  csrftoken = getCookie('csrftoken');
  $.ajax({
    type : "POST",
    datatype: "json",
    url: "/fav/",
    data: {
      song_id : song_id
    },
    headers: {
      'X-CSRFToken': csrftoken
    }
  });
  return false;
}
๐Ÿ‘คNab Ilovich

1๐Ÿ‘

first of all, you dont need <form> at all if you are sending the request with ajax.

secondly, you can set the csrf_token also in this way:

...
data: {
    csrfmiddlewaretoken: '{{ csrf_token }}',
    song_id : song_id
},
...

which always works for me.

๐Ÿ‘คdoniyor

Leave a comment