PhpRiot
Download This Article
Download this article in PDF format with all listings and files.

Price: $5.00 AUD
(Approx. $4.45 USD)

More information
Related Books
Prototype and Scriptaculous in Action [Ajax]

Prototype and Scriptaculous in Action [Ajax]

Prototype and Scriptaculous are libraries that extend standard Ajax. They make it easier to...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

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:

Listing 18 listing-18.js
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.

In This Article