Creating Sortable Lists With PHP And Ajax
Adding The Javascript Sorting Callback
The final item we must add is the JavaScript code to invoke processor.php when the list is updated. This involves creating a function that makes the Ajax update request, as well as telling the Scriptaculous Sortable.create() method about it.
Here’s the callback function:
function updateOrder() { var options = { method : 'post', parameters : Sortable.serialize('movies_list') }; new Ajax.Request('processor.php', options); }
Here we invoke the Prototype library’s Ajax request handler to call processor.php. Additionally, we use the serialize() method on the Scriptaculous Sortable object to create the POST variable we access in processor.php.
Finally, we modify our list creation to tell it about this updateOrder() callback:
Sortable.create('movies_list', { onUpdate : updateOrder });
The second parameter to Sortable.create() is an optional list of extra parameters. In this case we are just specifying the onUpdate parameter, which tells Sortable which function to call when the list is changed.
index.php for MySQL and PostgreSQL in full
require_once('database.php'); require_once('movies.php'); if (!dbConnect()) { echo 'Error connecting to database'; exit; } $movies = getMovies(); <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html> <head> <title>phpRiot Sortable Lists</title> <link rel="stylesheet" type="text/css" href="styles.css" /> <script type="text/javascript" src="scriptaculous-js-1.5.3/lib/prototype.js"></script> <script type="text/javascript" src="scriptaculous-js-1.5.3/src/scriptaculous.js"></script> </head> <body> <h1>phpRiot Sortable Lists</h1> <ul id="movies_list" class="sortable-list"> foreach ($movies as $movie_id => $title) { <li id="movie_ $movie_id "> $title </li> } </ul> <script type="text/javascript"> function updateOrder() { var options = { method : 'post', parameters : Sortable.serialize('movies_list') }; new Ajax.Request('processor.php', options); } Sortable.create('movies_list', { onUpdate : updateOrder }); </script> </body> </html>
Now, when you visit this page, you will see the list just as you did before, but now when you drag an item to a new location, it will be saved in the database. If you don’t believe me, try dragging an item, closing your browser, then reloading the page. The order will be just as you left it after dragging the item.




