Search code examples
javascriptsortablejs

How to submit newly sorted list of elements, with the library SortableJS


I am using the JS library SortableJS and trying to send the newly sorted array on submit.

The JS:

var originalArray;
var sortable = Sortable.create(selection, {
  handle: '.bars-move',
  animation: 150,
});

var modalForm = document.getElementById("modalForm");
  if (modalForm  !== null ){
    modalForm.addEventListener('submit', function(e) {
      var formData = new FormData(modalForm);
      e.preventDefault();
      var request = new XMLHttpRequest();
      request.open(modalForm.method, modalForm.action, true);
      var cookies = parse_cookies();
      request.setRequestHeader('X-CSRFToken', cookies['csrftoken']);
      request.onload = function() {
        /// send the new Array here
      };
      request.send(formData);
    });
  };

Any tips welcome !


Solution

  • The easiest way to do this is simply to submit the sortable array on submit :

    var sortable = Sortable.create(selection, {
        handle: '.bars-move',
        animation: 150,
      });
    

    and

    var modalForm = document.getElementById("modalForm");
    if (modalForm  !== null ){
        modalForm.addEventListener('submit', function(e) {
          var formData = new FormData(modalForm);
          e.preventDefault();
          var request = new XMLHttpRequest();
          request.open(modalForm.method, modalForm.action, true);
          var cookies = parse_cookies();
          request.setRequestHeader('X-CSRFToken', cookies['csrftoken']);
          formData.append('sortableArray', sortable.toArray());
          request.send(formData);
        });
    };