52 lines
1.4 KiB
JavaScript

import { getCookie } from './cookie.js'
const sorting_url = JSON.parse(document.querySelector('#sorting-url').textContent);
document.querySelectorAll('.sortable').forEach(el => {
const options = {
animation: 150,
store: {
/**
* Save the order of elements. Called onEnd (when the item is dropped).
* @param {Sortable} sortable
*/
set: (sortable) => {
const order = sortable.toArray()
const csrftoken = getCookie('csrftoken')
const data = {
model_name: el.dataset.model,
filter: el.dataset.filter,
filter_id: el.dataset.fid,
order: order
}
const options = {
method: 'POST',
body: JSON.stringify(data),
mode: 'same-origin',
};
// construct a new Request passing in the csrftoken
const request = new Request(sorting_url, {
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken
},
})
return fetch(request, options)
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
})
}
}
}
if (el.querySelector('.handle')) {
options.handle = '.handle'
}
new Sortable(el, options)
})