Introduction
If you have seen JQueryUI Sortable, you know that there is an easy way to implement drag&drop reordering of list items/components. If you have a set of items (e.g.
LI
elements) that are placed inside the sortable section (e.g.
UL
list) as the ones shown in the following listing:
<ul id="sortable">
<li id="item1">Item 1</li>
<li id="item2">Item 2</li>
<li id="item3">Item 3</li>
<li id="item4">Item 4</li>
<li id="item5">Item 5</li>
<li id="item6">Item 6</li>
<li id="item7">Item 7</li>
</ul>
You can convert this to the sortable list using the single line of code:
$("#sortable" ).sortable();
You can find live examples on the
JQueryUI Sortable demo site[
^].
Problem
Problem is how to persist order of the list elements once the list is updated? If you just let the JQuery UI sortable to reorder items in the list, the next time user visits the page original order will be restored.
Solution
The best solution is to create one server-side page (I will call it
persistListOrder.php) that accepts id of the list and array of the list item ids. Then you can put Ajax call in the update function of the sortable widget that will send new order of elements to the server-side page. Example is shown in the following listing:
$("#sortable" ).sortable({
update: function (event, ui) {
var list = $(this).sortable("toArray").join("|");
$.ajax({ url: "/persistListOrder.php",
data: {
'section':this.id,
'components': list
}
});
}
});
In this code, when the order of the sortable list is updated, ids of the list items are serialized to array separated with pipe separator. Id of the section (
UL
list) and list of ids is sent to the server-side page persistListOrder that will persist the changes. The parameter section is id of the list, and components is pipe-separated array of child items' ids.
This list can be saved into the database, and used to generated list on the server side when user visits the page again.