Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

With jQuery I'm retrieving positions of a sortable list using 'serialize', like this:

var order = $('ul').sortable('serialize');

The variable 'order' then receives the following:

id[]=2&id[]=3&id[]=1&id[]=4&id[]=5

Now how can I use this data in an ajax call?

This is how I plan to do it, but it's ugly and I can't change the parameter name 'id':

$.post('ajax.php?'+order,{action:'updateOrder'});

Maybe I need to unserialize, then implode the variable 'order' and assign it to just one parameter?


I don't have a problem with the server side code, but I have a problem with the jQuery client site code. The question is, where do I place the 'order' variable in the script?

In the example I gave I added it as a query string:

'ajax.php?'+order

But I would like to pass it as a parameter, just like the action parameter. The following doesn't work, it returns a syntax error:

$.post('ajax.php?'+order,{action:'updateOrder',order});

like image 761
bart Avatar asked Mar 17 '09 14:03

bart


4 Answers

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');
like image 60
bart Avatar answered Nov 17 '22 04:11

bart


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

like image 24
David Waller Avatar answered Nov 17 '22 03:11

David Waller


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
like image 24
Daniel Von Fange Avatar answered Nov 17 '22 04:11

Daniel Von Fange


var order = $('#projects ul').sortable('toArray'});

this might work too ;)

like image 6
Lyubomir Marinov Avatar answered Nov 17 '22 05:11

Lyubomir Marinov