Papermashup

Subscribe


Tweets


"@KBedders @elerichardson I'm Free!!!!!! Call / Whatsapp me!!!"

@ashleyford 2 weeks ago

"@KBedders moomin!"

@ashleyford 3 weeks ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Papermashup

Drag & Drop with PHP & jQuery

A drag and drop script that interacts with a MySQL database using PHP and JavaScript

AshleyAshley

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.

The Code


$(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 what’s going on in the code above.

  1. To start with we have a simple function that will slide up the ‘response’ div which contains the message once the data is saved in the database.
  2. We then move to the section that enables us to drag and drop the boxes. we then set the variable ‘order’ which contains the data to be posted via ajax to our database update script.
  3. Once the ajax request has been executed we then display the response in the div #response

This is the section in the index.php page that retrieves the results from the database in the correct order.



<?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 } ?>

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.



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';
}

demodownload

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 83
  • Ashif Zubair
    Posted on

    Ashif Zubair Ashif Zubair

    Reply Author

    how can we extend this logic for tree and branches drag n drop ?


  • Felipe Furlan
    Posted on

    Felipe Furlan Felipe Furlan

    Reply Author

    Excellent ! Simply and Work, thanks !


  • Mike McMonagle
    Posted on

    Mike McMonagle Mike McMonagle

    Reply Author

    Ashley – Can I suggest you create a small oval shape onscreen, then, with the font of your choice, type “benign genius” and press PRINT. Using a sharp pair of scissors (no running) carefully cut around the oval neatly, then, using double-sided tape apply it to your t-shirt or perhaps a favourite baseball cap.

    I just tried and amended this code to make an adjustable gallery upload and display within a bespoke CMS system for a client and she now thinks I am quite the most wonderful chap.


  • inam101
    Posted on

    inam101 inam101

    Reply Author

    Hello, it was a nice tutorial and a very useful control.

    I have a problem, whenever I click on a link inside the tab-body, it closes/hides the tab body instead of going to the desired destination page.

    Please help me with this.
    Thanks


  • Jeff
    Posted on

    Jeff Jeff

    Reply Author

    Hi,
    Great script!
    Maybe someone may help me, I am looking for a way to use drag and drop over a grid with different shapes library.
    Rectangles, squares of differents size picked up froma library and clipping together side by side over a grid.

    Anyone know how ?


  • gabstafari
    Posted on

    gabstafari gabstafari

    Reply Author

    just update the jquery ui and jquery to the latest version and it will work on all browsers.

    enjoy


    • Varinder
      Posted on

      Varinder Varinder

      Reply Author

      Wow !!!

      Thanks Now Its working on all browsers .


  • Varinder
    Posted on

    Varinder Varinder

    Reply Author

    Great work !!!
    Please share If you have any solution for IE9?


    • Ko
      Posted on

      Ko Ko

      Reply Author

      Yes, please…!!!!


  • John
    Posted on

    John John

    Reply Author

    This doesn’t work in IE9 ?


  • Dion
    Posted on

    Dion Dion

    Reply Author

    Hi,

    I love this tutorial, but i keep getting this error:

    Warning: mysql_query() [function.mysql-query]: Access denied for user ‘dionjo’@’localhost’ (using password: NO) in /admin/updateList.php on line 10

    Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /admin/updateList.php on line 10
    Error, insert query failed

    how can i fix this?


    • falconerie
      Posted on

      falconerie falconerie

      Reply Author

      you need it to edit the connect.php if you’re working on localhost, remove the password and change the user to ‘root’, change the database name.there you have it,


  • d33pu
    Posted on

    d33pu d33pu

    Reply Author

    awesome work :-)


  • no more black tea
    Posted on

    no more black tea no more black tea

    Reply Author

    IE9 breaks this. BUT it works in IE8


    • Varinder
      Posted on

      Varinder Varinder

      Reply Author

      Great work !!! but is there any solution for IE9?
      Please share……


  • oyun
    Posted on

    oyun oyun

    Reply Author

    Its a very nice tutorial. It worked like. IT worked all browser Mozilla, Chrome, ie.. thanx for sharing.


  • sabyasachi
    Posted on

    sabyasachi sabyasachi

    Reply Author

    This really help full thanks a lots


  • Paul
    Posted on

    Paul Paul

    Reply Author

    I like your drag and drop. I was wondering if there could be a way that when something else is added to the list, that what ever item is under the mouse is removed and replaced with whatever is with the mouse.
    Example.
    I have 10 items. I have another item from another div, that I want in my list, but I want my new item to replace one in my list.
    Is there a way to do that?

    Thank you in advance.


  • maxdimaz
    Posted on

    maxdimaz maxdimaz

    Reply Author

    Hi .. How About it in Div not in UL ???
    how to make im try

    $(#somediv div)

    not working??


  • Akki
    Posted on

    Akki Akki

    Reply Author

    Hi Its a very nice tutorial It worked like charm in Mozilla and safari
    Can you please make it work in IE . Databse is not getting updated while working in IE.
    Looking for a fast reply..
    Thanks


  • 35net
    Posted on

    35net 35net

    Reply Author

    It is very good, I like it much!


  • Joe Hooker
    Posted on

    Joe Hooker Joe Hooker

    Reply Author

    Your code isn’t displaying correctly. Thank you for the great tutorial though.


  • Orson
    Posted on

    Orson Orson

    Reply Author

    tks!!..so clear and useful


  • Ant
    Posted on

    Ant Ant

    Reply Author

    Hello, i keep getting this error –

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:wampwwwjquery-drag-dropindex.php on line 65

    what arnt i doing properly? i’m all good with php but tbh i never really dabble with databases too much, but i’ll take any advice i can get i seriously love this effect and want it working!


  • Michael
    Posted on

    Michael Michael

    Reply Author

    Hey,
    very nice. But: How to drag n drop between 2 columns. Making 2 columns no problem. But want to take one to the other. How ?


  • Iqrar
    Posted on

    Iqrar Iqrar

    Reply Author

    Hello Could you please show me how to do that with images. DRAG AND DROP IMAGES AND SAVE POSITION?


  • snappidagg
    Posted on

    snappidagg snappidagg

    Reply Author

    I’m using images in a list, how would I save their position in mysql based on their images names?


  • Cédric
    Posted on

    Cédric Cédric

    Reply Author

    Hi !

    Thanks so much for that script ! It really helped me !

    I’m building some kind of “favorite bar”. People can navigate in their private area and then they can create some “shortcut” for the categories they want by dragging them in a specific area without destroying it from its original location.

    Then if the client adds a shortcut item, it would add a new record in the database, and delete it if the client removes it from the toolbar.

    Actually I don’t really need to save to current position of each item of the list but I’d like to save the info “is in the shortcut toolbar or not ?”.

    I’d really appreciate if you had any kind of advice !

    Thanks a lot.

    Cédric


  • Juan
    Posted on

    Juan Juan

    Reply Author

    This is absolutely fantastic, thank you!!


  • Leyden
    Posted on

    Leyden Leyden

    Reply Author

    the file opens okay with 7zip


  • Mike
    Posted on

    Mike Mike

    Reply Author

    Your download folder is invalid or corrupt. FYI. Can’t download.


  • Rijo
    Posted on

    Rijo Rijo

    Reply Author

    Nice tutorial… but i want it something like if i drag and drop to another table then that item would be saved to another database table. how can i achieve this


  • Dhawal
    Posted on

    Dhawal Dhawal

    Reply Author

    hey…really good tutorial…
    thanks man for uploading this tutorial


  • vishal
    Posted on

    vishal vishal

    Reply Author

    nice tutorial.


  • Dior
    Posted on

    Dior Dior

    Reply Author

    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…


  • MundiSsa
    Posted on

    MundiSsa MundiSsa

    Reply Author

    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.


  • eric
    Posted on

    eric eric

    Reply Author

    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.


  • abdu.tursun
    Posted on

    abdu.tursun abdu.tursun

    Reply Author

    thanks!!!


  • Den
    Posted on

    Den Den

    Reply Author

    Hi Ashley! Nice tutorial! Thanks alot! Tell me please can I use it in commercial theme or plugin?


  • John
    Posted on

    John John

    Reply Author

    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?


  • trialanderror
    Posted on

    trialanderror trialanderror

    Reply Author

    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.


  • trialanderror
    Posted on

    trialanderror trialanderror

    Reply Author

    When trying to download sample, the zip file says its corrupted.

    thanks,


  • Indialike
    Posted on

    Indialike Indialike

    Reply Author

    Very nice and useful tutorials for web designers,
    Thanks for posting.


  • Ajmal
    Posted on

    Ajmal Ajmal

    Reply Author

    Thanks Ashley.
    I just need it same thing. Good Efforts. Thanks.


  • Enatom
    Posted on

    Enatom Enatom

    Reply Author

    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.


  • Enatom
    Posted on

    Enatom Enatom

    Reply Author

    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.


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Enatom No problem, happy to help. Please do post your solution up here. I’d be interested and im sure others will find it useful. Depending on how many users your going to have using this method it could get a little server intensive, it also depends on what server you have.

      Most quality hosts for example the mediatemple grid would be able to cope easily with hundreds if not thousands of simultaneous connections but it does depend on how efficient your code is.


  • Enatom
    Posted on

    Enatom Enatom

    Reply Author

    @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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Enatom so once you’ve added the code i wrote earlier, all you need to do is add the following to your updatelist.php file. Note that i’ve added mysql_escape_string(); this makes sure that no one can tamper with the data that is sent to the database.


      // here we save the posted data that was sent using javascript to the PHP variable $username
      $username = mysql_escape_string($_POST['username']);

      Once you add this line to the top of your update list page, you just need to add the queries that you posted originally and it should work fine.

      Let me know if that helps.


  • Enatom
    Posted on

    Enatom Enatom

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

      @Enatom in order to post the username variable to the php page you’ll need to replace the following two lines:


      // var username is dummy data
      var username = 'ashley';

      // you can see that i've added the value username to be posted to the php page.
      var order = $(this).sortable("serialize") + '&update=update' + '&username=' + username;

      Let me know if you have any problems. I haven’t tested this but it should work.

      Just an update, I’ve just tested the code, if you view the demo above and use firebug you can see that it posts the username ‘ashley’ to the update php page.


  • John S
    Posted on

    John S John S

    Reply Author

    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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @john The message in the demo is just to show you that your list order has been added to the database. you don’t need to refresh the page at all, all the requests are done via ajax.


  • Anton
    Posted on

    Anton Anton

    Reply Author

    Great work! I have one question. How to create sorting with 2 columns?


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Anton exactly the same as with one column, you basically need to duplicate the code but change the id’s and database, thats a dirty way of doing it, if your confident about editing JavaScript you’d need to modify the code to take 2 columns.


  • Alan
    Posted on

    Alan Alan

    Reply Author

    muy bueno amigo!!!
    super facil de entender y manipular. Exelente aporte!


  • Sunny Singh
    Posted on

    Sunny Singh Sunny Singh

    Reply Author

    Wish this was built with Mootools though, maybe I can try converting somehow but at least the sql is all there and stuff.


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @sunny converting this to Mootools shouldn’t be too hard i may even have a crack at it 😉


  • Peter
    Posted on

    Peter Peter

    Reply Author

    Nice post!! Thanks a lot


  • Brian Jørgensen
    Posted on

    Brian Jørgensen Brian Jørgensen

    Reply Author

    Awesome!

    Cool site btw – just subscribed to your rss !


  • Brian Jørgensen
    Posted on

    Brian Jørgensen Brian Jørgensen

    Reply Author

    Could you do it so you could add more, and delete? Would be so nice!


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Brian I’ll look into doing that when i get some time.


  • Brian Jørgensen
    Posted on

    Brian Jørgensen Brian Jørgensen

    Reply Author

    @Ashley – ah okay, now I get it.. Thanks :)


  • Felix
    Posted on

    Felix Felix

    Reply Author

    Realy usefull!!, thanks for share your code.


  • Brian Jørgensen
    Posted on

    Brian Jørgensen Brian Jørgensen

    Reply Author

    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 :o)


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Brian it means refresh the page to see that your changes have been saved in the database and that the list is in the same order that you put them in :)


  • Marc Falk
    Posted on

    Marc Falk Marc Falk

    Reply Author

    Lovely! Just what I needed, thanks…

    Nice blog by the way 😉
    Cheers!


  • Roy
    Posted on

    Roy Roy

    Reply Author

    Nice tutorial/howto, will try it tonight!

    Offtopic: “It‘s quite in here! Why not leave a response?” > quite or quiet?


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @roy thanks fixed the typo 😉