jQuery: What to do with the list that sortable('serialize') returns?

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');

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 '&'.


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