WpDoe WpDoe - 5 months ago 40
jQuery Question

jQuery sortable update the whole set of data

I have a HTML list like this:

<ul id="sortable">
<li class="ui-state-default" id="31">
list item
</li>

<li class="ui-state-default" id="32">
list item
</li>
<li class="ui-state-default" id="33">
list item
</li>
</ul>


and the following jQuery function:

$("#sortable" ).sortable({
update: function(e,ui){
$.ajax({
url:'/ajaxUpdateOrder',
data: {
id: ui.item.attr('id'),
position: ui.item.index()
}
});
}
});


It works fine, but what I need instead is to pass the whole set of
IDs
and
priorities
in order to update every record and not just the one thas has been dragged.

Any help or guidance is much appreciated.

Edit

With a lot of helo from one of the members, I have managed to modify the function like following:

$("#sortable" ).sortable({
update: function(e,ui){
var lis = $("#sortable li");
var ids = lis.map(function(i,el){return {id:el.id, priority:el.dataset.priority}}).get();
console.log(JSON.stringify(ids));
$.ajax({
type: 'POST',
url:'/BetterMeetings/meetings_tasks/ajax_update_order',
data: {
ids:ids
}
});
}
});


However, the data that I get in console is like this:

[{"id":"157"},{"id":"158"},{"id":"159"},{"id":"156"},{"id":"160"},{"id":"161"},{"id":"162"},{"id":"163"},{"id":"164"}]


so it is still missing the priority order.

Answer

You can add data-fields to your html tags:

<ul id="sortable">
    <li class="ui-state-default" id="31" data-priority="2">
          list item 31
    </li>

    <li class="ui-state-default" id="32" data-priority="4">  
           list item 32       
    </li>
    <li class="ui-state-default" id="33" data-priority="8">  
           list item 33
    </li>
</ul>

$("#sortable" ).sortable({
   update: function(e,ui){
     var lis = $("#sortable li");
     var ids = lis.map(function(i,el){return {id:el.id, priority:el.dataset.priority}}).get();
     console.log(JSON.stringify(ids));
     $.ajax({
       url:'/ajaxUpdateOrder',
       method:'POST',
       data: {
         ids:ids
       }
     });
   } 
});

Live on jsfiddle: https://jsfiddle.net/9kdqm98u/4/

As you see the array you post [{"id":"31","priority":"2"},{"id":"33","priority":"8"},{"id":"32","priority":"4"}] contains all the id-s in priority order (after I moved 33 to be the 1st one), so in the backend you have all the priorities in order according to this array.