scriptaculous sortables and PHP

[geek post, run away if you don’t like things like AJAX, PHP, MySQL, and other acronyms]

I’m developing a wiki/CMS hybrid for my new job. It’s pretty cool so far, but I wanted to offer an easy way for users to change the order of navigation items. For instance, if their navigation was originally displaying like this:

  • About Us
  • Contact
  • Documents

They may decide that “Documents” needs to move to the top, like this:

  • Documents
  • About Us
  • Contact

Enter Scriptaculous Sortables—the basic principle is simple. Make a list that you want to be sortable.

Sortable.create(‘navigation_list’, {onUpdate: updateNavigation});

‘navigation_list’ is the id of the element that contains your list. updateNavigation is the javascript function that is called when the list has changed. For this example, I have my HTML (generated from php, of course):


<ul>
<li id="nav_1" >About Us </li>
<li id="nav_2" >Contact </li>
<li id="nav_3" >Documents </li>
</ul>

and my javascript:


function updateNavigation() {
var url = "http://localhost/ajax.php";
var sorted = escape(Sortable.sequence('navigation_list'));
var updateNavigation = new Ajax.Request(
url,
{
method: 'get',
parameters: "sort_order=" + sorted,
onComplete: showUpdate

});
return true;
}

and my PHP:


$nav_order = 1;
$order_array = explode(",", urldecode($_GET['sort_order']));
foreach($order_array as $k=> $nav) {
$sql = "UPDATE navigation SET item_order = $nav_order WHERE navigation_id = $nav";
mysql_query($sql);

$nav_order++;
}
echo "Navigation order has been updated.";

I couldn’t get this to work using Sortable.serialize()- so I just use Sortable.sequence which gives me a comma seperated list, and then parse it with PHP.

Note: I hate how this wp plugin displays code. I’ll get around to making it pretty one day.

Advertisements

About andyhillky
I'm cool.

One Response to scriptaculous sortables and PHP

  1. Morten says:

    Genious mate!

    I also had serious issues getting Sortable.serialize() to work. Your example worked as a charm and made my day, thanx!

%d bloggers like this: