Coder1
Aricles and Screencasts by Mike Milano
Today is: 21 November, 2008
Check todays hot topics or new pictures
Aricles and Screencasts by Mike Milano
Today is: 21 November, 2008
Check todays hot topics or new pictures
JQuery Sortables with PHP and MySQL
I recently worked on a project which required an unordered list to be re-ordered and then saved. I wasn't about to make users enter numbers next to each item so I looked toward JQuery's UI library. Objective: We will display a list of fruit. The user can then drag the fruit and click a button to save the new order in the database. For this example, let's use a database table named fruit with the following fields: id, name, weight. Schema:
I'll begin with some very basic PHP to setup the scenario. This code queries the table ordered by weight. It then loops through and prints the result between list tags.
We're printing a list of fruit from the database ordered by weight. Now how do we re-order the list of fruit? Simple, JQuery Sortables. JQuery isn't going to do everything automatically. We still need to setup the form with input fields to submit the data. Let's take the last code block and add in hidden form elements which contain the value of each fruit ID.
Notice we used fruit[] as the field name for all the rows. When the form is submitted,l the fruit ids will be put into a PHP array in the order they appear on the form. i.e. $_POST['fruit']. Since PHP already handles that for us, we just need a way to move the list items around. You will need to download both JQuery and the JQuery UI. (yes, they are separate) You can download the full package, but for sortables, you only need these components: UI Core, Draggable, and Sortable. Let's finish our script by adding the JQuery and some PHP to handle the sort and update the database. Full Script (tested)
And there we have it. Now when you submit the form, it should re-sort your fruit, update the db, and the fruit list should be displayed in the new order after submission. Be sure to take a look at the JQuery Sortables documentation to see how much you can customize the behavior of the sort. With that and a little CSS, you can make this UI pretty sharp. |
|||
|
Copyright © 2008, Mike Milano
|
I believe I tested that code
I believe I tested that code when I wrote this. There's quite a few elements to this article, so maybe you could provide more info as to which part you're having a hard time with.
I can't get this to work.
I can't get this to work. Could you provide a working demo?
Thanks
Post new comment