An outline of what we are trying to achieve:
- Populate list values from a database and render them onscreen
- Create a server-side script that loops through the list updating the database with the new order
To enable this methodology there are several files:
Click here to download the necessary example files.
The updateList function sets a variable for the url used during the AJAX request before it calls Sortable.serialize passing the container ID as an argument to serialise the list to a format such as listContainer=5, listContainer=7, listContainer=2
The first three items of the list would be the items 5, 7, and 2 and the divs representing these items would have the following ID values: item_5, item_7, and item_2. This serialised list is set in the variable ‘params’.
Next an AJAX request is opened using Prototype’s Ajax.Request class. It is called with two arguments: the URL and an object with various options. The options include the type of request (POST in this example, parameters to pass the params variable and two functions (onLoading/onLoaded) that handle the showing and hiding of the ‘Updating database…’ div.
Normally in an AJAX request you would also add a callback for onComplete to handle the response from the server, but in this case the AJAX response doesn’t really matter because it is a one way communication in this demo. In a real application you would have more error handling and would need to correctly handle error conditions.
At the footer of the file there is a div with the ID ‘containerDiv’ which is the container for our list. Within this is some PHP that loops through an associative array and prints out each list item as a div with ID ‘item_10’ where 10 is the ID for that record in the database.
This file begins by calling session_start() to send the right http headers to prevent the file from being cached. Next it instantiates an object and calls the updateList method passing the listContainer variable from the POST request (containing our serialised list).
This is a simple db class that connects to the database and has methods to get and update the order of the list. In a ‘real’ application you should have a much cleaner implementation of the database access and would use other DB libraries to connect.