Getting an error const request = new Request( /* URL */, {headers: {'X-CSRFToken': csrftoken}} ); fetch(request, { method: 'POST', mode: 'same-origin' // Do not send CSRF token to another domain. }).then(function(response) { // ... });

I’m trying to build an add to card form with AJAX and I get this error when I click the add to cart button

Error:

Forbidden (CSRF token from POST has incorrect length.): /inventory/product/
this-is-a-test-product/{% url "inventory:single_product_add_to_cart" %}
[05/Sep/2023 01:18:23] "POST /inventory/product/this-is-a-test-product/%7B%
%20url%20%22inventory:single_product_add_to_cart%22%20%%7D HTTP/1.1" 403 25
29

Form:

    <form action="{% url 'inventory:single_product_add_to_cart' %}" method="POST">
            <label for="select">Qty</label>
            <select id="select" class="h6 store-select-dropdown">


                {% for i in gogo %}
                      <option value="{{i}}">{{i}}</option>
                {% endfor %}
            </select>

      <button type="button" class="" value="{{product.id}}" id="add_button">Dropship</button>


</form>

JS


$(document).on('click','#add_button', function(e){
	
	e.preventDefault();

	
		$.ajax({
			type:'POST',
			url: '{% url "inventory:single_product_add_to_cart" %}',
			data: {
				productid: $('#add_button').val(),
				productqty: $('#select option:selected').text(),
				csrfmiddlewaretoken: '{{csrf_token}}',
				action: 'post'
			},

			error: function (xhr, errmsg, err){}


		});
	


})

Any idea what causes this or how to fix?

Thanks in advance

It’s because CSRF is to be sent with your post request, from the official docs you can see how to send CSRF with AJAX How to use Django’s CSRF protection | Django documentation | Django