Creating Sortable Lists With PHP And Ajax
Adding Drag And Drop Functionality To Our List
We will now add the drag/drop functionality to our list, as well as applying CSS styles to the list. At this point the ordering of the list will not be saved, as we will do this in the next step.
Installing Scriptaculous
Since we are using Scriptaculous to create the drag/drop effect, we must now download and install it. Note that we also need the Prototype library, however, this is included with the Scriptaculous download.
This example uses Scriptaculous 1.5.3.
Once downloaded, extract the library in the directory where you saved index.php. You may save this elsewhere, but we will assume this is where you have saved it.
Styling the list – styles.css
Before we add the drag/drop, we will style the list. Below is a generic CSS class we will save to a file called styles.css.
.sortable-list { list-style-type : none; margin : 0; } .sortable-list li { border : 1px solid #000; cursor : move; margin : 2px 0 2px 0; padding : 3px; background : #f7f7f7; border : #ccc; width : 400px; }
The Scriptaculous drag sort code
It’s really simple to make our list drag-sortable. At this point we’re not actually saving the drag changes, but to make the list sortable, the following code is used:
Sortable.create('movies_list');
The name _movies_list_ refers to the ID of our unordered list.
There are many more options and effects that can be applied, but the default options work just fine for what we’re doing. You can always read the Scriptaculous documentation for more options.
Our new index.php
So here is the new version of index.php, with styles added, Scriptaculous and Prototype loaded, and our draggable list created:
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"> Sortable.create('movies_list'); </script> </body> </html>
Note that we also added an ID to each list item, as these are the values that will be passed to the form. Note that these IDs — and the ID of the list — should use underscores as separators, not hyphens.
So at this point, if you view this page, you should be able to drag the items in your list up and down! Cool eh?

![Prototype and Scriptaculous in Action [Ajax]](http://ecx.images-amazon.com/images/I/51i%2BlUTDmbL._SL75_.jpg)