I wrote ajax for django to add products to cart, I use internal js which runs but when I put that code in external js file it doesn't work, Although I received the ID and csrf_token.
html
<main data-item-id="{{ product.id }}" data-csrf-token="{{ csrf_token }}">
javascript
$(document).ready(function(){
var btn = document.querySelector(".add-to-cart");
var productId = document.querySelector('main').getAttribute('data-item-id');
var csrfToken = document.querySelector('main').getAttribute('data-csrf-token');
btn.addEventListener("click", function(){
$.ajax({
type: 'POST',
url: '{% url "cart:add_to_cart"%}',
data: {'productId': productId},
headers: {'X-CSRFToken': csrfToken},
success: function(data){
$("#total-items").text(data.total_items);
}
})
})
})
also the script and jquery are defined.
{% url "cart:add_to_cart"%}will not resolve into your original URL because Django template engine does not parse JavaScript files you've to load your URL in HTML file so Django-Template engine will resolve it for you.