Dynamic Drag’n Drop With jQuery And PHP
After publishing ScheduledTweets yesterday, I received e-mails asking "how the drag'n drop & saving the new positions to the database was working".
We create a simple database as below:
The most important column in the database is
recordListingID which shows us the order of the records.
This feature can be applied to any table by adding such a column to it.
We'll be using an unordered list that is generated from a PHP query that lists the items according to the
recordListingID value mentioned above.
Here it is:
We will be using jQuery UI's sortable plugin.
We made the unordered list inside
#contentLeft a sortable item, used the
serialize function of jQuery to create the array and posted it to updateDB.php.
After posting the array of "new order of the items" to updateDB.php, we must run a query to update our database that will reflect the last positions of every item:
‘; print_r($updateRecordsArray); echo ‘
echo ‘If you refresh the page, you will see that records will stay just as you modified.’;
You can see that this is the easiest part. We handled the array as
$updateRecordsArray and used it inside a
for each statement.
With a new variable named
$listingCounter, while the
for each statement runs, we have updated the values of
recordListingID column of every item in the database with
$listingCounter values. And that's it.