1

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.

2
  • Are you sure the external js file is included? Can you also post the script tag? Did you check the console to see if the js file is actually requested? Commented Jan 5 at 11:30
  • {% 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. Commented Feb 1 at 14:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.