Parsing jQuery’s sortable(“serialize”) Method with PHP (and symfony)
First time here? Subscribe to my
RSS feed or
follow me on Twitter.
Thanks for visiting!
It looks like as of jQuery version 1.2.6 there’s no built in way to serialize a sortable object into a javascript array for use in ajax calls.
This example uses symfony-specific code, but you should be able to use this method in any type of php scripting. Here’s some example HTML from the template where we’re going to make the ajax call:
<ul id="item_list">
<?php foreach ($items as $item): ?>
<li id="item_order_<?php echo $item->getId() ?>"><?php echo $item->getName() ?></li>
<?php endforeach ?>
</ul>
And here’s our ajax call from within the template:
$('#save_btn').click(function(){
$.post("<?php echo url_for('collection/reorder') ?>", { item_order_str: $('#item_list').sortable("serialize") });
});
Unfortunately, this simply sends a string of key/value pairs to the server under the variable name item_order_str. It would be nice if there was a serializeArray method for sortables in jQuery just like there is for inputs. That way php would automatically create an array of values for us but, luckily, PHP has a function for dealing with variables in this format: parse_str
Here’s the example symfony action for dealing with this string:
public function executeReorder()
{
$item_order_str = $this->getRequestParameter('item_order_str');
// this will generate $output['item_order'] from the string sent by the ajax call
parse_str($item_order_str, $output);
// do something with item_order... this is just an example:
foreach ($collection->getItems() as $item)
{
$item->setSortOrder(array_search($item->getId(), $output['item_order']));
$item->Save();
}
$this->renderText('Success!');
return sfView::NONE;
}
The reason the name of the outputted variable from parse_str is item_order is because each of the li tags has an id prefixed with item_order_ and jQuery automatically parses that attribute and creates the key/value pairs accordingly which turns it into something like this:
item_order[]=10&item_order[]=9&item_order[]=4&item_order[]=2&item_order[]=13&item_order[]=3&item_order[]=16
A couple of notes: You can change the way this string is generated by jQuery. See the documentation for more info. Also, the array_search method is handy for returning the key of an associated item. I’m using it above to find out where in the sorted array my item is so that I can update its sort_order field.
Update: I edited the parse_str usage in the above example so that all of the variables expanded from the function are captured in $output.

5 Comments
Jump to comment form | comments rss | trackback uri