Creating Sortable Lists With PHP And Ajax
Summary
In this article we learned how to create a sortable list using PHP and Ajax. We used Scriptaculous and Prototype libraries to make light work of our JavaScript requirements (the sorting and Ajax requests), as these libraries provide a very powerful and simple interface to advanced features and effects.
Error handling
We didn’t deal with error handling at all in this article, for the sake of simplicity. Specifically, we didn’t specify what would happen if the update didn’t work. If the update failed, the list would appear to be updated, but when you refreshed the list it would be the old state.
One possible way to handle this would be to send a success/failure indication from processor.php, and then to read this response in index.php, rolling back the drag and drop if failure was returned.
Extra features
When you update the list, the saving of the new ordering is a very quick process, but it is possible that sometimes it could take longer due to latency or server load. As such, you might think about showing then hiding a message while performing the update.
To do this, you would make the message appear when updateOrder() is called, and then create another function to hide the message once complete. This is achieved by specifying the onComplete parameter in the options array for the Ajax request.
Here’s an example:
function updateOrder() { // turn on update message here var options = { method : 'post', parameters : Sortable.serialize('movies_list'), onComplete : function(request) { // turn off update message here } }; new Ajax.Request('processor.php', options); }
I’ll leave this as an exercise for you to complete. Hint: create a div which you initially set the CSS display property to none. Then set it to block to show the div, and set it back to none to hide it again.
Other Options
- Download a PDF version of this article
- View or post comments for this article
- Browse similar articles by tag: Ajax, JavaScript, PHP, Prototype, Scriptaculous
-
Read related articles:
- Eight Weeks of Prototype: Week 5, Ajax with Prototype
- Reminding Users to Submit Forms
- Monitoring File Uploads using Ajax and PHP
- Eight Weeks of Prototype: Week 2, How Prototype Extends Elements
- Eight Weeks of Prototype: Week 8, A Complete Prototype Example
- Eight Weeks of Prototype: Week 7, Other Prototype Functionality
- Eight Weeks of Prototype: Week 6, Writing JavaScript Classes with Prototype
- Cloning Google Suggest With Ajaxac
- Eight Weeks of Prototype: Week 4, Event Handling in Prototype
- Eight Weeks of Prototype: Week 1, Beginning with Prototype


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