Extending the jQuery Sortable With Ajax & MYSQL

I’ve had a lot of response to the jQuery sortable list post I wrote a while back, and a lot of them ask how to send the results to a database. I’ve often said the best thing to do would be to update it by AJAX, but I’ve never really explained how. So here it is!

There was a bug a few people noticed with the new jQuery UI a short while ago that stopped the update callback working. That bug has since been rectified and all is kosher again. I have since updated the example to the latest jQuery and UI downloads. The examples and downloads have also been updated accordingly.

Step one: Create the page with the sortable, and the CSS

(described on my previous post) We have however altered it slightly, so here is the updated code (without any css, the css is in the sourcecode)
Include your javascript files, you’ll need jQuery and the jQuery UI files

Then you’ll need to create your Javascript function. We’re going to listen for the list to be updated, then call the php page, pass it the new order by GET and update the #info div with whatever the PHP file prints out:

Now here’s the HTML to output the list etc. etc:

Step two: Create the PHP to handle the serialized list jQuery has created

The PHP page will simply take the url it’s been handed and pick out the items from the array. You can then manipulate your database with the new values, or just format however you want. The code could look like this:

You could then happily run each sql statement. Although it should be said that this is not recommended where possible, always sanitise your query, and preferably use an object relational mapper.