
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Sortable - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css"> <style> #sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; } #sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; } #sortable li span { position: absolute; margin-left: -1.3em; } </style> <script> $(function() { $( "#sortable" ).sortable(); $( "#sortable" ).disableSelection(); }); </script> </head> <body> <ul id="sortable"> <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li> <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li> <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li> <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 4</li> <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 5</li> <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 6</li> <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 7</li> </ul> </body> </html>
Some JS is to be added so that the order preference which is made, is saved somewhere, either in the database or as cookies. Let's see how.
Add this script in the main code:
$('#element').sortable({ axis: 'y', update: function (event, ui) { var data = $(this).sortable('serialize'); // POST to server using $.post or $.ajax $.ajax({ data: data, type: 'POST', url: 'URL-HERE' }); } });
URL-HERE is to be replaced by the PHP file's address which will save the preference order somewhere. The preference order as in the form of an array. So, when you use the serialize option, it will create a POST query string like this: item[]=1 & item[]=2 etc. So if you make use, for example, your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
For example, in that PHP file, you're going to write something like this, if you are saving the preferences in your Database.
<?php $i = 0; foreach ($_POST['item'] as $value) { // Execute statement: UPDATE DATABASE or something else $i++; } ?>
The UPDATE statement can be like:
UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
And if you're going to save them as cookies then you can use, for example,
<?php $i = 0; foreach ($_POST['item'] as $value) { setcookie("cookienum".$i,$value,time()+3600*24*30); } ?>
This is how you can save the order preferences from jQuery UI Sortable.
0 comments