'Uncaught ReferenceError: csrftoken is not defined
I'm trying to create a shopping cart for my website using java script and django. But when I click on the "add to cart" button, i get an error Uncaught ReferenceError: csrftoken is not defined at updateUserOrder (cart.js:28:19) at HTMLButtonElement. (cart.js:14:13) in console, which refers to the code X-CSRFToken :csrftoken. file cart.js:
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function () {
var productId = this.dataset.stuff
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser') {
console.log('User is not authenticated')
} else {
updateUserOrder(productId, action)
}
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')
var url = '/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
base.html:
<script type="text/javascript" src="{% static 'js/cart.js' %}">var user = '{{request.user}}'
function getToken(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// 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 = getToken('csrftoken')
</script>
{% endblock content %}
button:
<button data-stuff="{{stuff.id}}" data-action="add" class="btn btn-outline-secondary add-btn
update-cart">Add to Cart</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
