I found several posts in relation to my question, but none of them solves my problem. I am sending data to the server but I keep getting a 403-error with an error-message that complains about the csrf_token.
Here is my html:
<ul id="EditorNav" class="editor-nav">
<form id="NavItemsEditorForm" class="nav-items-editor-form">
{% csrf_token %}
<!-- {{ form }} -->
{% for item in pages %}
<input class="editor-nav-input" type="text" value="{{ item }}"/>
{% endfor %}
</form>
<img id="Plus" class="plus" src="{% static 'img/plus.png' %}" alt="Plus" title="Een menu-item toevoegen" />
<img id="Shuffle" class="shuffle" src="{% static 'img/shuffle.png' %}" alt="Shuffle" title="Verander de volgorde van de menu-items" />
<button id="NavEditReady" class="nav-edit-ready">Klaar</button>
</ul>
I created a view and added that view to the urlpatterns-arrau in urls.py. Here is my javascript:
jQuery.each( jQuery( '.editor-nav-input' ), function( i ){
let data = {}
if( jQuery( this ).val() === '' )
{
jQuery( this ).remove();
}else{
const idx = jQuery( '.editor-nav-input' ).index( this );
const tekst = jQuery( '.editor-nav-input' ).eq( idx ).val();
data = {
"id": idx,
"tekst": tekst,
"href": tekst.replace(/\s/g, '_').toLowerCase(),
"volgorde": idx + 1,
};
formdata.push( data );
}
});
console.log( formdata );
// Stuur de data naar de server:
jQuery.ajax({
method: "POST",
url: "/pagepost/",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: formdata,
dataType: "json",
success: function( response ){
console.log(response);
},
error: function( err ){
console.log( err.responseText );
}
});
I have tried different ways of including the csrf-token to the data as a seperate object. But nothing works. Any help is appreciated.