The ability to drag and drop content on a page and have it save the order can make for a great user interface and is actually relatively easy to execute with a few lines of jQuery. You’ll need to include the jQuery user interface library which you can find here: Jquery Google API. All the files needed to get this up and running are in the download at the bottom of this post.
In this tutorial we’re going to be looking at 2 main PHP pages. the index.php page which contains the contents and functionality to perform the drag and drop and the updateList.php file which is a simple piece of code to update the listOrder column in the database using PHP and MySQL. Additionally you will need to add your database details to the connect.php file in the download package.
$(document).ready(function(){
function slideout(){
setTimeout(function(){
$("#response").slideUp("slow", function () {
});
}, 2000);}
$("#response").hide();
$(function() {
$("#list ul").sortable({ opacity: 0.8, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&update=update';
$.post("updateList.php", order, function(theResponse){
$("#response").html(theResponse);
$("#response").slideDown('slow');
slideout();
});
}
});
});
});
Here’s a summary of whats going on in the code above.
This is the section in the index.php page that retrieves the results from the database in the correct order.
<div id="list">
<div id="response"> </div>
<ul>
<?php
include("connect.php");
$query = "SELECT id, text FROM dragdrop ORDER BY listorder ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$id = stripslashes($row['id']);
$text = stripslashes($row['text']);
?>
<li id="arrayorder_<?php echo $id;?>"><?php echo $id;?> <?php echo $text;?>
<div class="clear"></div>
</li>
<?php } ?>
</ul>
</div>
Below is the code from the ‘updateList.php’ file. Its pretty self explanatory, we have a MySQL update script wrapped with a foreach loop which adds the list order number in the database and echo’s the response.
<?php
include("connect.php");
$array = $_POST['arrayorder'];
if ($_POST['update'] == "update"){
$count = 1;
foreach ($array as $idval) {
$query = "UPDATE dragdrop SET listorder = " . $count . " WHERE id = " . $idval;
mysql_query($query) or die('Error, insert query failed');
$count ++;
}
echo 'All saved! refresh the page to see the changes';
}
?>
This entry was posted in Downloads, Javascript, PHP, Tutorials, Web Tools, jQuery, popular and tagged Downloads, drag, drop, Javascript, jQuery, PHP, Tutorials. Bookmark the permalink.
Nice tutorial/howto, will try it tonight!
Offtopic: “It‘s quite in here! Why not leave a response?” > quite or quiet?
Lovely! Just what I needed, thanks…
Nice blog by the way ![]()
Cheers!
Hey, thanks.. It’s very nice man – but it says “Refresh the page to see the changes”, but when I refresh, nothing happens?
Thanks for it though
)
Realy usefull!!, thanks for share your code.
@Ashley – ah okay, now I get it.. Thanks
Could you do it so you could add more, and delete? Would be so nice!
Awesome!
Cool site btw – just subscribed to your rss !
Nice post!! Thanks a lot
Pingback: Twitted by UltraMegaTech
Wish this was built with Mootools though, maybe I can try converting somehow but at least the sql is all there and stuff.
Pingback: LimeSpace – IT » Die Links der Woche – Urlaub im August
Pingback: 10 jQuery code snippets a programmer need daily | PHP tutorials and Scripts Collection
muy bueno amigo!!!
super facil de entender y manipular. Exelente aporte!
Great work! I have one question. How to create sorting with 2 columns?
Hi,
Beautiful. Any reason why you didn’t have a meta refresh built in? I know that’s what I’d like to do, but don’t know how to do it. The manual refresh kind of breaks the automagic coolness of this.
Thanks,
John
Hi,
Where it says (in updateList.php) :-
$query = "UPDATE dragdrop SET listorder = " . $count . " WHERE id = " . $idval
How do I send it another clause, so I can update the order of specific users own posts.
I want it like this:
$query = UPDATE dragdrop SET listorder = " . $count . " WHERE id = " . $idval." AND username=".$USERNAME
im not sure how to pass that extra field (username) to updateList.php through from index.php.
I hope you can help..
enatom/com
@Ashley
so how would the PHP variable look like when taking in the javascript “username” var.
I mean how would the SQL query look like in UpdateList.php ?
i havent dealt with javascript and php interaction like this before.
thanks
Just wanted to say thanks, I haven’t tried it yet, but I think it will work.
For the sake of anyone following this, ill post the results back in about 2 hours time.
But, I think that this will have a tremendous effect on the Database. If only it had a save button instead of AJAX, anyway. I got the bare bones of how this work, so now since i know how it works, thanks to you.. I could improvise with it.
Thanks alot for this drag and drop feature.
Absolutly amazing Ashley, thanks alot for this. It all worked out well. .. it was just a case of adding the extra field for the username clause.
All in all jQuery syntax is still quite hard to understand with the )}; flying everywhere, but i hope to learn it all.
Again thanks.
Thanks Ashley.
I just need it same thing. Good Efforts. Thanks.
Pingback: 30+ 新鲜惊奇的 jQuery æ’件与教程 | 芒果
Very nice and useful tutorials for web designers,
Thanks for posting.
When trying to download sample, the zip file says its corrupted.
thanks,
Ok i figure it out.
when i downloaded the zip file it kept telling me it was corrupted.
but when i unzip the file again, it gave me all the files i needed.
thanks,
going to tryit.
Is there anyway to convert this into multiple tables? For example, I’m trying to make a Team Picker (I’ve got everything working but the DB update). I would like 3 boxes, one for all the members and 2 more boxes for Teams. Using your drag and drop the user could take members from the first box and add them to a team. It would save to the DB and then next time the user comes back to the site she could see her teams she picked. Is this possible with your code?
Hi Ashley! Nice tutorial! Thanks alot! Tell me please can I use it in commercial theme or plugin?
thanks!!!
Hey, thanks using this was a snap after hours lost in trying to find a simple and efficient list ordering solution. One question though, how can you possibly get it to work with pagination/paginated data say for instance you are dynamically generating the list from a table with 30 list items and you paginate with 10 per page and you are trying to:
1. retain the overall order but change the order of the ten items in view (i.e. working on 2nd page with list items 11-20 reorder just that without influencing the rest of the pages){one way – get position of the first list item from db and equate to dollar count, is there a better way? }.
2. reorder list items across the pages i.e. list item 12 in page 2 to move to list item 3 in page 1{possible solution but unable to work it out: move list item to top/bottom of page and have a link to move it up/down which swaps it with the last/first item on the previous/next page}.
Any ideas would be greatly appreciated.
Olá Ashley,
Excellent tutorial, I would like you to do a few more models of this function. How, drag the box freely and have the option to delete any box if you wish.
I’m using this tutorial to see her if I can do what you say. If case you prepare a new tutorial or just know where some of the form that said, I would like to be informed.
Congratulations on your Blog has an excellent range of scripts.
i want to put a condition for drag, for example if (ID < 5){let it drag}
just run the action on items that meet the condition.
Thanks…
nice tutorial.
Subscribe to all the Papermashup Tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
Follow us on Twitter and get in-stream messages
48 discussions around Drag & Drop with PHP & jQuery