I am trying to create a Django form with dynamically filled fields: that is, when one field ( checkin_type) is selected in the drop-down menu , other fields are automatically filled with the corresponding data. To this end, I would like to send a POST request to the server as soon as a drop-down list option is selected.
So far I have tried the following template (following https://docs.djangoproject.com/en/2.0/ref/csrf/ ):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script>
$(document).ready(function(){
var csrftoken = Cookies.get('csrftoken');
$(".auto-submit").change(function() {
$.post({
url: "{% url 'get-checkin-type' %}",
data: $(".auto-submit option:selected").val(),
headers: {
X-CSRFToken: csrftoken
}
})
});
});
</script>
<form action="" method="post">{% csrf_token %}
{% for field in form %}
<div class="{% if field.name == 'checkin_type' %}auto-submit{% endif %}">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
<input type="submit" value="Send message" />
</form>
However, when I select the drop-down list, I get
new: 17 Uncaught SyntaxError: Unexpected token -
which comes from the line X-CSRFToken: csrftoken:

- , ? ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_token, ).
, , jQuery CSRF $.post() , CSRF POST data, , ,
: XMLHttpRequest X-CSRFToken CSRF.