With jQuery I\'m retrieving positions of a sortable list using \'serialize\', like this:
var order = $(\'ul\').sortable(\'serialize\');
The vari
The best way is know to use var order = $('ul').sortable('serialize');
feature is shown in the following link :
http://blog.arnaud-k.fr/2010/09/29/tutorial-jquery-trier-une-liste-en-dragndrop-avec-jqueryui-sortable/
All you need to get the ordered list data in your php file is the code :
foreach( $_POST['id'] as $order => $order_nb )
{
...
}
I think the best way is not to use sortable('serialize')
at all, but use jQuery to simply iterate over the sorted ids, like so:
order = [];
$('ul').children('li').each(function(idx, elm) {
order.push(elm.id.split('_')[1])
});
$.get('ajax.php', {action: 'updateOrder', 'order[]': order});
This has an advantage over explicitly appending the serialized sortable to the URL (or a parameter) in that it doesn't include the order[]
parameter at all if there are no li
in the list. (When I had this problem I was using sortable(connectWith: 'ul')
so it was entirely possible for a user to drag all the li
from one list). In contrast appending the serialized sortable would leave an unwanted '&'.
Regarding the "key" param I used the square brackets in order to get an array.
var data = $('#cms-form').serialize();
data += '&' + $('.ui-tabs-nav').sortable('serialize', {key:'nav_order[]'});
if data is
$data = 'album[]=stat&sort[]=157204&sort[]=157205&sort[]=157206&sort[]=157208&sort[]=157207&sort[]=157209&sort[]=157210&sort[]=157211&sort[]=157212&sort[]=157213';
and you want to get sort as array in php
use parse_str()
parse_str($data, $output);
print_r($output);
Output : Array ( [album] => Array ( [0] => stat )
[sort] => Array
(
[0] => 157204
[1] => 157205
[2] => 157206
[3] => 157208
[4] => 157207
[5] => 157209
[6] => 157210
[7] => 157211
[8] => 157212
[9] => 157213
)
)
Lets say you were ordering news items, and your page sent this to "?id[]=2&id[]=3&id[]=1&id[]=4&id[]=5" your php code.
$_POST['id'] # would be [2,3,1,4,5]
// Now we need to update the position field of these items
foreach($_POST['id'] as $i=>$id ):
// For our first record, $i is 0, and $id is 2.
$post = Post::get($id); # Do you own database access here
$post->position = $i; # Set the position to its location in the array
$post->save(); # Save the record
endforeach
Found it! I needed to add the option key:'string'
which changes the variable name to 'string' instead of 'id'.
var order = $('#projects ul').sortable('serialize',{key:'string'});
$.post('ajax.php',order+'&action=updateOrder');