This question probably has been answered but I cant seem to figure out how to implement js-cookie inside of my code. My goal is to have a csrf token for an ajax call or whatever its called (I’m sorta new) because the error I was getting was not having a csrf token. I’ve downloaded js-cookie with npm into my project but I’m not sure if I’m supposed to link it to the page with a script and src tag. And now I’m getting an error: “Uncaught TypeError: $.cookie is not a function” Any ideas?
Here is my html file (Just the body) which has the links to jquery and the javascript page :
<body>
...code...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="staticfiles/item-store.js"></script>
</body>
Here is my Javascript file :
//Creating CSRF Token
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
// Send info to Python File
function Send_Python_Info() {
ToSend = JSON.stringify(item_mode)
console.log(ToSend)
window.alert(ToSend)
$.ajax({
url:"/test",
type:"POST",
contentType: "application/json",
data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
data: JSON.stringify(ToSend),
success: function () {
alert("Saved!");
}
});
}
Thanks for your time!