Dynamic Drag’n Drop With jQuery And PHP

76°

After publishing ScheduledTweets yesterday, I received e-mails asking "how the drag'n drop & saving the new positions to the database was working".

Drag'n drop generally looks hard-to-apply but it is definitely not by using JavaScript frameworks. Here is, how it is done by using jQuery & jQuery UI:

jQuery Drag'n DropjQuery Drag'n Drop DemoDownload

The Database:

We create a simple database as below:

jQuery Drag'n Drop Database

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.

The HTML:

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:

[sourcecode language=”php”]

  •  

[/sourcecode] 

The JavaScript:

We will be using jQuery UI's sortable plugin.

[sourcecode language=”javascript”] [/sourcecode]

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.

The 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:

[sourcecode language=”php”]
‘; print_r($updateRecordsArray); echo ‘

‘;
echo ‘If you refresh the page, you will see that records will stay just as you modified.’;
}
?>
[/sourcecode]

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.

  • Very nice trick, but may I suggest serializing the unordered list items into a string like “1,3,2,4”, and save this one into a separate table ?

    This way, you only have to do one query to the mysql server when saving, and one query when retrieving the order, plus you can use the “ORDER BY FIND_IN_SET(recordListingID,’$order’)” where $order will contain “1,3,2,4”.

  • JW

    Thank you for providing this!
    I’m looking to use this in part of a photo list reordering admin area for a client. Should fit the bill quickly and perfectly.
    Cheers!

  • @Robert,
    I was stuck in-between whether to store them in a single field like you mentioned or to go with the method in the article.

    Decided that both can have their advantages in a web app (like getting the order of a single item) & gone with this.

    I definitely agree with the amount of queries you mentioned in updates. And had never used FIND_IN_SET. Thanks for that as well :).

    @JW,
    Great to hear that it will be helpful.

  • @Umut M.
    Well the “store in one field” method is way much better if you have to deal with large sets of data, like for example, a list of products in an online shop, where sometimes, in a category you can have like, let’s say, 50 – 60 products, if not even more. Instead of doing 50 update queries, even if the queries are on an loop, is far much “sane” to just do 2.

    On the other hand, the original method is far much better when you have to deal will small sets, where you won’t see the difference between 2 and 10 queries.

    One last thing, that I had to take in consideration, and I bumped into it a lot in the last years, is the “childish” behavior of the clients when you handle them such “toys” in the back-end administration, and they play with it all the time 😉
    x queries * y arranges due to the client’s indecision/fun = dead mysql server

    So basically you have to use the one that fits you and your client best.

    Cheers!

  • KPR

    Great article, and all of the comments so far are all great as well, especially the on on the users playing..I do agree as well as a second table for order just to save server hits.

  • @Robert, @KPR,

    Totally agree with you. For small amount of records, I’ll store the “order” for every item in the “items” table to reach the “order” faster & store them in an other table for larger amounts of data.

    Yes, clients love to play with drag’n drops. And it is great that they generally don’t have Firebug installed, else they could have played more :).

  • Excellent work, I have been waiting to find something like this. i have seeen methods using the cookie plugin, but never an AJAX request.

    Ill make sure to keep this in mind for projects. Im gonna download the code and play around with it.

    Ryan

  • mario

    Uh nice. Except the PHP code with SQL string concatenation. Ever heard of escaping (amateur method) or parameterized queries (professional programmers)?

  • Dhanu

    Pretty nice article.
    Just a little, question i have, i am having dataset like 30 records which needs drag n drop, so, for each drag drop procedure, i am sending the list through Ajax with backend to update DB positions.

    do you think, 30 records are much enough to bottleneck the mysql server , as each drop will have 30 updates statements in loop.??

    any suggestion, appreciated

  • @Dhanu,

    It is generally 2 things that bottlenecks database servers: amount of queries + the frequency of them.

    If this is a feature at the frontpage of a popular website that everyone can play with, then yes. Else, I’m pretty sure 30 update queries won’t bottleneck a MySQL server.

    But if there is a possibility that there may be much more records, then I suggest following Robert’s route.

  • Dhanu

    @Umut M.

    So far i am seeing only the cases like 30-35 queries per request, but now i am implementing a check for example, if you have more than 50 or 60 items in list, i will ask user, please remove some elements, to be able to get use of this kool feature of drag n drop …:)

    safe our db…

  • Zmip

    @Robert in comment #1: Robert, you should really read up on thes subject of database normalization and learn that creating compound data like you suggest is a no no. Furthermore, read the MySQL documentation on INSERT INTO table (field1,field2) VALUES (), which takes 1 query and inserts millions of rows in one query. For updating, there is INSERT INTO … ON DUPLICATE KEY variant, which will not insert, but rather update millions of rows in one query.

  • Czkoudy

    Hello, i´m wondering if i can put and instead of and ? Is that possible and what part of code should I change? Thanks

  • Czkoudy

    Hello, i´m wondering if i can put tr and td (table row) and instead of ul and li (list)? Is that possible and what part of code should I change? Thanks

  • @Czkoudy,

    Although I’m not sure if it will work, it may.

    It is hard to explain the parts to be changed in detail but you simply need to change the ul-li codes in the index.php & updateDB.php.

  • Pedro Pinto

    Hello,
    Great piece of code!
    I’m wondering if there is some way to create new positions with the DB Inserts…
    Thanks

  • @Pedro,

    Can you please explain it more?

  • jackson

    How to do with multiple columns? Lets say left, mid and right column, how to save to database?

  • A great little piece of code. It came in very useful when developing a basic portal for showing me how to store the x and y positions! Thanks a lot

  • W3

    thanx, i find what i want.

  • sanjay

    that custom jquery.ui.js is almost 56kb which is very very large for normal sites…
    so can any body make a more custom js file for it….?
    any body…
    removing unnessary parts

  • I just stumbled across this. I’ll have to give it a try when I get home as I have been wanting to implement something like this on a project I am workiong on.

  • jon

    Hi I just came across this article and plan to use part of it in my music server. I’m searching for a way to make a Drag n drop playlist. Is there anyway to take the item from one DB table and add them to another DB table. Maybe have two list and drag n drop between them, one would be all the available choices and the other would be the finalized list. Any help would be greatly appreciated

  • @jon,

    Although I can guess that it must not be that complicated, I have never moved objects between 2 lists and don’t know the limits there.

    I have used jQuery Sortable in this article & you may want to check the features of it here: http://docs.jquery.com/UI/Sortable which might give an opinion about the answer.

    And, if you manage to do it, would be great if you share your experiences here. Bests.

  • ziad

    very nice, gr8

  • Is there any way to replace an item in the list rather that reordering it. ie replace 1 with 4

    Great article by the way, I’v been having a good play and can see a lot of possibilities

  • Mike

    Thank you very much for this tutorial, I am now playing with incorporating it into my admin interface. One problem I’ve stumbled on is utilizing multiple instances. I am using a combination of JQuery’s accordion and this, with the accordion instances displaying the names of my categories, and then when you click on it, it opens to display the list of products in that category, which I want to be sortable. I can easily pass category names by appending them to the array ([0] => 48.8) and then processing with php, but not being very familiar with Javascript, I am having trouble with passing more parameters to the function itself, such as the names of the div to sort? (contentLeft_1, ontentLeft_2, and so on)? Thanks!

  • @Paul,
    If I didn’t get the question wrong, I believe you can do that on the query side. But as far as I know “sortable” doesn’t support a replacing effect so you may need to do that on the server-side & may be update the look (Ajaxed) to reflect the replaced version.

    @Mike,
    I have just checked the serialize event again but seems like you can’t send 2 different arrays.

    You may go with a trick and create the array name like catName_Cat1-recordsArray_1 and use toArray (http://www.jqueryui.com/demos/sortable/#method-toArray) & create a function on the PHP side to split the contents and run the query accordingly (what I wrote may be totally wrong but looked logical to me :)).

  • Mike

    @Umut M.

    I may have expressed my idea wrong – I don’t really need to send two arrays to php simultaneously. What I am trying to achieve is to pass a parameter to the Javascript function so I can have several instances of “contentLeft” div’s on the same page. It works just fine, however, only the first instance really works. I am sitting here thinking of how to trick it, but my Javascript skills are below average to say the least 🙁

    In essense, I am thinking of making unique div names with PHP (thus, each sortable is in its own uniquely identified DIV) and then pointing the main function to the correct div when it is being sorted, so the part of the function with $(“#contentLeft ul”).sortable … is replaced with $(“#contentLeft_1 ul”).sortable, $(“#contentLeft_2 ul”).sortable and so forth.. I just don’t know how to pass this sort of parameter to it… Sorry for the confusion here, I am not a native english speaker… Let me know if any more clarification is needed, and I’ll upload what I got so far somewhere.

  • @Mike,

    Hmm, got it.

    You can create a function which does the following:
    Once an user clicks inside an accordion level, it reaches to the parent elements id (category in your case) with jQuery’s “parent” selector & creates a custom function with that value like: $(“#contentLeft” + customValue + “ul”).sortable)…

    I may be missing something here but can see that if you’re not that familiar with JS, this may be a headache to create.

    If you won’t have too many accordion levels, you can create js functions for each level like:
    $(“#contentLeft1 ul”).sortable…
    $(“#contentLeft2 ul”).sortable…
    $(“#contentLeft3 ul”).sortable…

    & it will work, although it won’t be the best coding pattern.

  • Mike

    Thanks, I think I see what you mean. I’ve thought of creating multiple functions, just don’t like the idea of something less than perfect 🙂 I might settle for it for now, but ideally, I think I’d love to try your approach with the parent call (once I know what that is). I imagine many people out there might have this problem, plus, I foresee myself utilizing the same for other sections of my site, where there might be many more categories, so a universal function would still come in handy. Here’s what I got so far, simplified (just the output, no database there, but hopefully gives you the idea…) http://stereo80s.com/jdd/index.html
    Would really appreciate a quick and dirty solution 🙂 Thanks!

  • Oh, just thought that they don’t even have to click on the accordion level, what if it was triggered by them clicking inside the sortable instance itself? Then it’d be like the ultimate sortable plugin with unlimited uses!

  • khan

    Hello
    First I say thank for you for writing this great tutorial.
    Using your source code I apply on my structure but one problem is coming.
    I want I use your tutorial for simple html without using their table or using separate table in which simple recordID and recordListingID is it possible? Actually on which structure I want to apply your tutorial this data structure(on which structure i apply drag and draw ) is coming from different tables. Is it possible

  • This is realy Such a nice thing to shareeeeee . Great sharing

  • thank you very much. good job…

  • ziad

    sorry if its duplicated but i typed a wrong e-mail address
    hello,
    i have managed to get a list from an XML file, but i m having problem updating the listing in the xml file! any help plz.
    thanks

  • ziad

    youppi, i did it myself:D:D
    i can now load data from xml files and able to reorder them changing nodes…

    its just great:D

    thanks

  • @ziad,
    Great to hear that. Congrats 🙂

  • fede

    very good but not working on firefox 3 🙁

  • Blake

    It’s working just fine on Firefox 3. Turn on javascript…

  • This is the best drag and drop explanation by far – thanks!

  • I am still reading about drag’n drop with jquery, but till now your explanation is one of the best.

  • http://www.dhtmlgoodies.com/scripts/drag-drop-nodes/drag-drop-nodes-demo3.html

    Umut – I have been trying to get similar functionality as shown in the link above – but not able to follow how to send the info to a MySQL table.

    I would like to have the following :
    1 – 1 list of items to drag
    2 – 2 containers to drag them to
    3 – Once each item has been dragged over to each list – the item goes away
    4 – Once this is complete – have the option to write each of the 2 containers into tables

    Any ideas?

    Again – great tutorial to get me started with jQuery!

  • Ruben

    Hi,

    is there anyway to make some items on the list not movable?

    thanks

  • Akhil

    I have tried your code and it is working fine for the first drag and drop action. After that it is not working. I tried with get method than post and what i saw is after the first action, the ” recordsArray ” value is not passing, it seems as undefined. Can some one help me on this issue

    Thanks

  • Akhil

    I kept the php code in the middle of the file and so in the jQuery Ajax response, the whole file content are retrieving and because of that the code was not worked as I mentioned in my previous comment. I tried now by kept my php code at the top most of the page and so it is working fine now

    Thanks
    akhi

  • @Akhil,

    Is this the demo that you’re having the problem or a local installation (are u having the problem with the demo)?

  • Akhil

    @ Umut M

    I tried it in localhost and it is working fine now as i updated the code as i mentioned in my last comment.

    Thanks for your quick reply

  • @Akhil,

    Great to hear that. If not using Firebug, definitely suggest it as it can show the responses better to quickly analyze such problems.

    Bests.

  • beguinner

    Hello
    Thanx for your code it’s works fine. I have a question : Is it possible to refresh the drag and drap sorting list (div contentLeft in the example) with ajax. I try to make a simple document.getElementById(‘contentLeft’).innerHTML=. Display is good but drag and drop doesn’t works. Anybody has an idea ?
    Bests.

  • beguinner

    Gary, I have the same problem like you

  • Efe

    Good Work.!!

  • Khoa

    i’m not download code!

  • nico

    este es un plugin para jquery facil de usar jQPOOOP y carga por ajax y texto simple que enconte el otro dia
    http://www.dieroboter.com/jQPOOOP
    or
    http://code.google.com/p/pluginjquery

  • chand

    Hi everybody,

    Please if any one of you guys, knows, such an example with flash please let me know which is dealing with flash and php I’ll be very very grateful to you.

    Thanks

  • hitek

    i tried making my list from left to right, but the script breaks when I do it. any suggestions?

  • @hitek,

    I can’t see any reason as it is the list that matters rather than how it is styled.

    I suggest that checking jQuery’s sortable if there is anything special with horizontal lists.

  • asma

    I tried this code for drag and rearrange page numbers.I have In one container 2 page no’s..Hence I recode ajax page for updating database.. I used div tag instead of li tag.Its working in internet explorer 6.0 only. Mozilla, safari chrome didn’t work.No request gone when dropping the pages.Any suggessions plz..

  • asma

    Hi friends,
    I used the div tag for displaying the list from left to right, So I gave div style as style float:left; So the when i drag it comes there itself..No request gone because of this stlyle float left..Any Suggession for breaking float left

  • @asma,

    “floats” can be problematic w,th interaction.

    For a horizontal list, if you try a CSS like: http://css.maxdesign.com.au/listamatic/horizontal01.htm I believe you may have a better chance to make it work.

  • asma

    Hi,
    I tried this style.It is working the li tag contains text..In my Li tag contains set of div tags..Any possibility to display Set of divs in horizontal direction without using float:left and position absolute

  • cok cok teşekkürler arkadasım

  • hi, very very thank you good job…

  • Anton

    Thanks works fine 😀 Just what i neded!

  • Matt

    Thanks, saved me a lot of time. Works Great.

  • Nick

    I’m developing a card game for a child cancer research study and this is the closest thing I’ve found to what I need. Thank you so much. The question I have is how to go about having the list items, rather than being resorted, be dragged into 5 multiple choice positions. There are 110 question cards the child is asked to place in 5 positions from Never to Always. Any help would be much appreciated.

  • @Nick,
    I think starting from this example would be wrong for your needs.

    You can easily accomplish what you’re looking for with the jQuery UI’s droppable. Take a look at the examples here: http://www.jqueryui.com/demos/droppable/#default

    It is highly customizable and well documented. Hope it helps.

  • Nick

    Umut, Thanks. Yes, I’ve used that site to get the where I am so far with the project, which is everything but sending the location of all of the dragged cards to a record within the db. There is a deck position they start of stacked in, a choose not to answer position, and then the Never, Rarely, Sometimes, Often, Always positions. I’m sorry if this is off topic; the part of this code here that I liked is the AJAX that sent the position of the dragged object to the db, also that it generated the objects from a db; I’ll definitely use those. It’s the object buckets, so to speak, that is the main challenge. Thanks again.

  • Fantastic tutorial, top notch and very easy to implement. This has really opened up the door to me for how easy it is to do behind the scenes updating using php/mysql! Thanks!

  • This is really a fantastic tutorial and very easy to use.

    Thanks for sharing this helpful PHP tutorial with us….I am ready to use for my website.
     
    Thanks one again

  • Chris

    Great article, just wondering if it would be possible to easily combine this with input fields as well?

  • Eddie

    The code works great when I use unordered lists. I just tried it on code that had tags and it won’t work. Can I not drag/drop p tags?

    Thanks!

  • Very nice! I’m using this on my custom homepage to help enhance the link dock.

  • Mentor Gashi

    Hi Robert I need :$ a little help if you could help me or anyone that could help me anyway, I am making a web application and now I used this drag and drop tool just the same but the matter is that the storing procedure should run after the user clicks on the buton Save the list.
    I tried in many ways but the order value of javascript isn’t appearing to me I tried to make a session with its value and when user clicks save I tried to update that session to database but the value of that kind that javascript makes php can’t face it or I don’t know how to end this.

  • @Mentor Gashi,
    You can call the serialize function when you click the “save button”.

    The code below:
    var order = $(this).sortable(“serialize”) + ‘&action=updateRecordsListings’;
    $.post(“updateDB.php”, order, function(theResponse){
    $(“#contentRight”).html(theResponse);
    });

    is triggered when the drop is completed. You must remove it from there and add it to your save button’s “click” event.

    Hope it helps.

  • Mentor Gashi

    @ Umut M.
    Thanks a lot for your reply Umut, but I tried as you said but didn’t work because when you take this code:
    var order = $(this).sortable(”serialize”) + ‘&action=updateRecordsListings’;
    $.post(”updateDB.php”, order, function(theResponse){
    $(”#contentRight”).html(theResponse);
    });
    out from that function part it doesn’t know what value does have this $(this).sortable and what to serialize.

  • @Mento Gashi,

    You’re right with that. Although haven’t tried, using the id or class of the

      rather than “$(this)” may work like:

      $(“#id-of-the-div”).sortable…

      If it doesn’t work, I suggest you check the jQuery UI documentation for that, must be something close..

  • Mentor Gashi

    Thanks a lot for your help 😀

  • Mentor Gashi

    I made it using cookie 😛 (TSK UMUT) 😀

  • tope adefokun

    this is helpful, im lovin it!

  • masd

    Hi,

    Great script, thanks a lot !!!

    I have some data stored in each ,and problem appears on tablet pc, as I cant click on links. Is it possible to dissable draging when you click on link in

  • Maurits

    Can i use a instead of a ?
    e.g.

     

    Coz most data is putted in tables

  • David

    Hey,

    I’m trying to apply this to my code and I can’t seem to be able to apply this to tables and inner div. (I have changed the $(“#contentLeft ul”) to $(“#contentLeft div”), $(“#contentLeft table”) and it doesn’t help)

    I’m trying to add the ability to sort images on my gallery pages.

    The images along with their (delete, show/hide) links are in a div that contains a table. And while it does allow me to drag it won’t make space for it nor will it allow me to drop for resorting. This only seems to be working with lists (ul, li) is there a way to make this work with divs and inner tables.

    Any ideas?

    Thanks,
    David

  • @David,

    I’m not sure if tables are supported to be drag’n dropped by jQuery UI, never tried it.

    I suggest that you check the jQuery UI docs for that.

  • I may have missed it in the documentation/comments, but is there a way to make a value of the array non-draggable?

    I would like to use this for clients to arrange records, but I would like to control which ones they can and cannot arrange depending on certain variables.

  • DeeDee

    Hi!

    Thank a lot for the script!

    I´m just playing around and have a question:

    How do I modify the function, if I want to transfer another variable?

    The tablename “records” should be variable. I have modified the MySQL-Statement in updateDB.php, “catch” it with “$table = $_POST[‘tab’];… But what do I have to do, to get the variable “tab” in the Poststring?

    (At the end, I want to create various tables…)

    I´m sure it´s a pretty simple solution.

    The question above is also very interesting.

    (…and sorry for my poor English.)

    Best wishes
    DD

  • kb

    Hi! Thanks for a great post! I’m just curious; how come you wrap it all inside a function() in the document.ready()?

  • Angela

    Hello everyone,

    Is there a way to assign a value from my database to the array key instead of it auto-incrementing from 0?

    I suspect it’s something to do with the JavaScript.

    I’m a student and am implementing this script into a project. Any help would be appreciated.

    Thank you!

  • Jayaraj

    Thanks, Thanks for the script

  • Pete

    Great Article, however you’re update script is vulnerable to sql injection…

    mysql_real_escape_string($_POST[‘action’]);

    with magical quotes phasing out this is critical…

  • @Pete,

    Thanks very much for that. Just updated it.

  • Paul

    Very nice, Thanks.

  • Mike T.

    I am attempting to use this more than once on a page, so for 2 different lists. The first list will work, but the second will not. If I remove the first, then the second will work. The I modified the jquery so that it is different enough, at least I thought I did. Any advice on how to get this to work for more than one list on a page?

  • Mike T.

    Nevermind. It seems to work now. Not exactly sure what the issue was.

  • Tom

    Hi,

    I wonder how could I modify the “onmove” javascript at start to send to the server side php just the released position.

    EG:

    I move element 8 to position 3, I want to send to my php, only the number 3.

    Anybody can help with this ?

  • Anna

    I have been trying this for hours and it will not update the database. Did anyone else have this issue with the downloaded code?

  • Den

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

  • @Den,

    Yes, sure. Go ahead (and hit the jackpot) :).

  • Arne

    Thanks, there are many tutorials on this method, but this is the one that works. Easily downloadable ZIP with all necessary files, including an SQL query to create the database. People should always do tutorials like this.

  • eric

    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 $listingCounter, 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.
    Note: Pagination would also reduce the number of queries run.

  • Eric,

    Seems like you’ll have to make a custom trick there:

    1.
    – Let’s say you’re on page 2 where the recordListingID starts with 11.
    – Make this 11 a variable in PHP.
    – After the drag’n drop there will be an array from 1-10. You’ll have to update your recordListingIDs with 11+array (and maybe -1, depending on how you shape it).
    – To sum up, you only need to know where your recordListingID starts in that specific, paginated page.

    2.This will go beyond tricky but if you like digging the code and cracking keyboards, you can combine this demo with http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/ which can end in something awesome.

  • eric

    Thanks a lot Umut, for the script and reply. Will definitely check it out, try it, post back and give credit on success.

  • adel

    thank you

  • vedran

    any success eric ? 🙂 i’m trying to do exactly the same thing. thanks

  • sanae

    i want to know if we will use an form and what is the parameteres to put in action and method???

  • Leigh

    Great code – worked nicely with my product categories.

    How would this work if I had nested lists?

    So 4 levels of categories?

  • Michael

    hey, thanks a lot, great article 🙂 !

  • Oscar

    I agree with Zmip in that a single INSERT query to update all order id’s is better in any case than a single query per row or Robert’s idea to serialize in one field.

    A single query can be used like:

    INSERT INTO
    table (recordID, recordText, recordListingID )
    VALUES
    ( $recordID1, ”, $recordListingID1 ),
    ( $recordID2, ”, $recordListingID2 ),

    ON DUPLICATE KEY
    UPDATE recordListingID = VALUES( recordListingID );

    and as long as recordID is a unique key, it will update all recordListingIDs in one query.

    Cheers

  • Oscar
  • Majid

    Hi, very nice ,

    It’s possible to do the samething in java jsp ?

    thanks

  • Great tutorial, Thanks

  • Aayushi

    Hi, thanks a lot. Save my a lot time.. !!!

  • Thanks for this wonderful script..

  • I’m trying this system with c #. But [‘recordsArray’] is empty, constantly sending. A definition that does not exist in code recordsArray .. I could not understand the rate?

  • Supper code of Drag’n Drop With jQuery – worked nicely with with my project thanks allot.

  • Steve

    The link for the code no worky.

  • Cary Siegler

    Anyone have any ideas how this can be used on a iphone/ipad?

  • CACA-COBRA

    I could not find how to download.

  • @CACA-COBRA,

    Once subscribed to our RSS feed and while reading it from a feed reader, it can be found at the bottom of any post under “Special Downloads”.

  • I need this but with MooTools, please?

  • Nice post, I am doing something like this but this method is much nicer, will alter my code.

  • Christian Houmann

    Well I might be a bit old fashioned (in cyberspace year 2K is the middle age…) but I use classic ASP and I’m happy with it. Now I need to do exactly what this script is able to do.
    Does anone know how to convert the PHP part to ASP, or is able to explain how to?

  • Hi, very nice ,

    It’s possible to do the samething in java jsp ?

    thanks

  • @Mert,

    The answer should be “yes”:
    – JavaScript
    – Dynamic server-side language. Just convert the PHP code to any other language you prefer

  • Marco

    Hi, i’m Marco and i’m italian. (i use a translator, sorry)

    This script it’s so cool, but:

    It is possible to save the positions without list?

    If yes, how?

  • Raul

    Exelente, but what if I want to do a query DESC? I need to make any changes to the code???????

  • @Marco,

    As far as I remember, jQuery UI doesn’t force using “li”s. I suggest checking the sortable and draggable widget docs for using them on other elements.

    @Raul,
    After a quick look, I don’t think so.

  • Yahya

    Well, i am trying to use this code in a article manager. But it is not working – actually i couldn’t make it work.

    Here is the code:

    [code]

    <li id="recordsArray_”><?php echo $kimlik . " ” . $makaleintrobasic; ?>

    [/code]

    And this is updater php.

    [code]
    require(“conn.php”);

    $action = $_POST[‘action’];
    $updateRecordsArray = $_POST[‘recordsArray’];

    if ($action == “updateRecordsListings”){

    $listingCounter = 1;
    foreach ($updateRecordsArray as $kimlikValue) {

    $query = “UPDATE icerikdb SET siralama = ” . $listingCounter . ” WHERE kimlik = ” . $kimlikValue;
    mysql_query($query) or die(‘Error, insert query failed’);
    $listingCounter = $listingCounter + 1;
    }

    echo ”;
    print_r($updateRecordsArray);
    echo ”;
    echo ‘If you refresh the page, you will see that records will stay just as you modified.’;
    }

    [/code]

    Where I am wrong. Thanks for help.

  • David Tompkins

    Thanks for this code, it’s great and I’m really hoping I can get this to work and save it as code I can reuse. I tried recreating the code exactly as you have it, using mySQL, without luck. I’m getting this error no matter what I try….

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/content/f/r/e/frederickweb/html/church/index.php on line 98

    Appreciate any suggestions…

  • Mike

    This is a wonderful demo. Very helpful. Can you help me figure it out for my own implementation? Here is my PHP code which initially creates a bunch of divs(lines) that are drar-and-droppable.
    <?php
    $query = "SELECT name, measurement FROM events";
    $result = mysql_query($query);
    if($result && mysql_num_rows($result) != 0) {
    echo "”;
    $i = 1;
    while($row = mysql_fetch_assoc($result)) {
    $id = “check” . $i;
    echo “” . $row[‘name’] . “”;
    $i++;
    }
    }
    ?>
    However, you pass over recordsArray. What should I pass over to the updateDB page?
    Thanks
    Mike

  • Mike

    New question, can someone explain to me where “recordsArray” is that the author is posting to PHP page? I’ve done plenty with PHP and posting, but I don’t understand this one.
    Thanks
    Mike

  • @Mike,

    Just like the article explains, the “serialize” function of jQuery converts the list into an array.

    It is all this line:

    “var order = $(this).sortable(“serialize”) + ‘&action=updateRecordsListings’;”

  • Mike

    Thanks for the reply Umut. I got that part figured out. Now I’m having a problem with my Mysql. As it is, the query just sets the dragged row orderID to the same as one already existing. I found some code to increment all the records in the database at once. But I need to know the id of the item that was dragged. Any way to pass that ID to the update page?
    Thanks much!

  • @Mike,

    I’m not sure if jQuery UI widgets have this built-in.

    You can try to get it with standard jQuery events like getting the ID of the item clicked, etc.

  • Thanks. This is what I was looking for. Thanks to the author for publishing this.

  • jamjanek

    Great technique.
    Im very thankful for the Author.
    I’ve been using it with sql so far, but now i decided to go further with xml.
    Thanks again.

  • JimBobUK

    This is awesomme! I got this working with a mysql database of my own no issues at all. My next thoughts on this are as follows:
    currently the records are displayed:
    Record 1
    Record 2
    Record 3

    I would like to look at displaying records as:
    Record 1 | Record 2 | Record 3

    I have tried looking at horizontal loopers but cannot get this to work.
    My current code is as follows:

    <li id="recordsArray_”>

    <a href="” target=”_blank” class=”outerLink”><img src="http://www.bitpixels.com/getthumbnail?code=58234&size=200&url=” width=”200″ border=”1″ class=”darkableImage” onmouseover=”this.style.opacity=0.6;this.filters.alpha.opacity=60″ onmouseout=”this.style.opacity=1;this.filters.alpha.opacity=100″/>

     

    Any help on this would be gratefully received.

  • @JimBobUK,
    Doesn’t it work without any updates to the code but only updates to CSS for displaying the list horizontally?

  • JimBobUK

    @Umut M
    I would not know what to look for or what to change in CSS, I havent changed the CSS from the original so any pointers would help.

    Cheers

  • @JimBobUK,

    If I’m not wrong, adding “display:inline” to “#contentLeft li” in CSS should do the trick

  • Liam

    How can I implement several versions of this when using a header file. Maybe I could pass a variable into the JS in the head to say which table I want to update. Im not sure how to do that though.

    Thanks

  • @Liam,

    Just target the list with a unique identifier like it exists in the example in lines:

    $(“#contentLeft ul”).sortable

    You can duplicate the JS code and wrap items inside new elements like:
    $(“#newDrag ul”).sortable

    Or, like you said, the best way would be making the line:
    $(“#contentLeft ul”).sortable
    dynamic as possible. You can get the parent element of a list onClick and assign it to the function.

  • pablos83

    Hey, I’ve got a problem. I drag and drop item from list and it makes my page blank (like loading other page but not exactly, because it never loads any results), and appears to loading something but it never does. What am I doing wrong?

  • wr

    This works just as advertised, but I was just wondering if it could be made more efficient by only sending down the ids of the items that were just swapped in the list. As I see it, it is unnecessary to update all the items’ sort order in the database when really only 2 of the items in the list need to have their sort sequences swapped. Thanks for any suggestions!

  • wr

    Actually, I just realized that it isn’t really swapping 2 items in the list, rather it’s pushing everything up or down to fit the new item, so really, every sequence would need to change on every list item between the original position and the new position. I made it slightly more efficient on the server by saving the previous positions in the session. This way, if the item is only dragged a few positions away from it’s original position, then only those few records need to be updated.

  • @wr,

    That’s for sure a smarter way, specially for a huge list of items.

  • i know this is an older post but i’ve been looking all over. I remember reading this when it was first posted. Anyway, jquery is awesome, and this drag and drop is what I needed for a website design client…thanks.

  • Chris L.

    Wow, really like this! I was looking for this such a long time… 🙂

  • This is an old post, but to all those that are coming here for a solution, you can do the update via a single query by using the T-SQL switch.

  • Damn… I can’t post code here, but here is a link with the code http://pastebin.com/Qm7sSdNE

  • elp

    well, although this is an old post. but i like it. it’s awesome.

    let say i put those drag n drop menu on a form, what if i save the list into cookies first. then, after i close the form, it will update it’s position into database. avoiding some “nasty” user to play with it 😀

    sorry for my english, i hope you understand for what i mean….

  • Thanks for the great script. Since I’m going to be updating the order of my things like once a month, I’m not really worried about efficiency in the back end, however for the sake of others, it would be nice if you could make this function return the change as opposed to the whole list? For example, move item in position 1 to position 3 and have “itemid=someid&start=1&finish=3” sent to ajax or something similar.

  • This is a great script. It’s exactly what I need except for one thing: I’d really need the order numbers to be updated as the items are dropped so the user can see that the changes where effective. How can I achieve that?

  • Amy

    This was amazingly helpful. Thanks so much for posting.

  • nonab

    ok first of all i have to say that i love this script
    i was trying to change the way of showing the items.
    i’d like it to be like a table:

    item 1 | item 2 | item 3
    item 4 | item 5 | item 6…

    but when i put those in a table and i try to drag any item it drag’s whole table instead of one item.
    would you give me any hint on how to acomplish this?

  • nonab

    ok i managed to do it after checking sortable documentation:)

  • Check out the newer version with SQL Record Saving for all users at: http://www.eyedeyeah.com/?p=27

  • Chris

    Hey! Hopefully a few folks are still watching this thread! This is a great script-Shef, thanks for the code to convert all the mysql updates into one-it works perfect!

    Question-has anyone managed to get this to update the order numbers as soon as a list item as dropped? The question was asked already, but I don’t see a response…

  • Chris

    GOT IT! – How to dynamically update the order numbers as list items are dropped

    Ok, took me all day, and I may have worn out google, but I got it.
    One of the first things I did when I got this script working was to get rid of the green array display-‘contentRight’. Once it was working, I didn’t need it, and if I really need to see that info, I can turn on Firebug, right?
    But that little array is important: it shows that this javascript already has data being returned to the main page! It is that little bit at the end of the javascript:
    [code]
    function(theResponse){
    $(“#contentRight”).html(theResponse);
    [/code]

    It was feeding the array from updataDB.php, called ‘$updateRecordsArray’ back to the main page. And just displaying it with tags.
    Well, couldn’t ‘theResponse’ send just about anything back? Yup.

    So I had to set up the main page-I took all of the php that created the unordered list-everything in ‘contentLeft’ basically, between the tags. I took it out, put it in its own php file, and then called it back into that div with an include. Still works exactly the same, obviously.
    But now the div ‘contentLeft’ has content dynamically targeted to it.

    Next change: in updateDB.php, I got rid of the array at the end-the tags and everything in between. I put the same ‘include’ that is on the main page back in there.
    (due to some variables, I also put sessions in place to carry my variables around without having to use any ‘form’ elements. But you may not have to do that.)
    Once that was done, I made one last little change to ‘function(theResponse)’ – I changed ‘contentRight’ to ‘contentLeft ul’.
    Now, when I drag a list item it calls updateDB.php, and thanks to Shef, my database is hit with only one query. And the javascript ‘response’ is to send the same include that I just modified right back to the place where it started-the contentLeft ul div, only this time it has my updated order in place!

    End result-I can drag and drop list items, and the row numbers appear to dynamically change as each item is dropped. JQuery is refreshing the with the list every time I drop an item, without reloading the page. And since my variables are floating in session-land, I don’t get a box asking me to resend data either.
    Whew!

    next task-get this thing to understand tactile input for iphones and ipads!!
    Again, thanks to Umut and Shef. You guys wrote some cool code!

  • Chris

    One more upgrade:
    the list is likely populated by text, so on mouseover, the pointer becomes a text bracket. Changing that to a ‘hand’ pointer, indicating the ‘draggable’ nature of the list items, is very easily done:
    In the tag for each item, put this:
    onmouseover=”document.getElementById(this.id).style.cursor=’pointer’;”
    voila, you get a hand pointer over each list item, click and drag away…

  • Chris

    that should read, in the “li” tag…

  • Prasanna

    How to do with multiple divs? Lets say I have three divs with different categories(Public,private,protected). It should be drag and drop between these three divs as well sorting in respective divs and how to identify changing between three divs to save to database?

  • Thanks for this script! It’s simple and neat and works well. I’m using it for sorting images.

    Like David above, I had difficulty getting this to work in a table, but it is doable. jQuery’s sortable() function expects to operate on list items, but it can operate on other HTML elements.

    $("table#my_id").sortable({'items':'tr', opacity: 0.6, ...});

    Because you’re not operating on list items (the default), you need to specify what you are operating on (in this case, table rows).

    Hope that helps!

    TRiG.

  • Note: You need to update to jQuery UI 1.8.15 for this to work in IE9.

    TRiG.

  • clestial

    When I update the sort order of lists like this, I usually go with a different approach, using only three queries, regardless of how long the list is.
    $oldIndex is where the moved row started at.
    $newIndex is where we want to move the row to.
    $recordId is the ID of the row.

    UPDATE list SET sortindex=sortindex-1 WHERE sort > $oldIndex

    This moves all rows with sortindex higher than $oldIndex “up” one step (like we would have to do if we are deleting a row)

    UPDATE list SET sort=sort+1 WHERE sort => $newIndex

    This moves all rows with sortindex higher or equal to $newIndex, creating an open space for the row we’re moving (like we would have to do if we are inserting a new row somewhere)

    And the last query
    UPDATE list SET sort=$newSort WHERE recordId = $recordId

    This sets the sortindex to where it should be on the row we are moving. And we are done.

    So, instead of running one query for each row in the table, these three will do the job just as good.

  • Maria

    Thanks a lot! This is pretty neat!

  • Ali

    How to disable sortable after the sort. Please help me

  • doogie

    I get the following error in index.php page:
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /var/www/projects/phptraining/dragndrop_test/index.php on line 98

    Any Ideas?
    Thanks

  • doogie

    Never mind – got it: I added
    or die(“Query failed with error: “.mysql_error()) to line 96:
    $result = mysql_query($query)

    seems I misspelt the db name!

    Doogie

  • Kristof

    when testing your script, it drags and drops as wanted.

    but when the items-to-be-dragged are placed at the bottom of my html page and – after scrolling – the ContentWrap is moved to the top of my page, it goes wrong. meaning, the item dragged at THAT moment is no longer visible, until it’s dropped. it looks like that THAT item is placed at about 400 pixels too high during dragging. any help ? my DIV’s and SPAN’s and other closing tags are okay …

  • Kristof

    It’s solved !
    This was my first line in the html page :

    Removing this line solved the issue. 🙂
    Anyone an idea why ? What should I put here ?

  • Kristof

    Oh my … it didn’t insert all of my text. Hope this one does …

    < !DOCTYPE html PUBLIC ´´-//W3C//DTD XHTML 1.0 Strict//EN´´ ´´http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd´´ >

  • Could this be built into an array that looked something like a bar chart? Maybe 12- 15 columns? Could you drag an item from one column into another one?

    When you get past the sql and php I am really over my head.

    Thanks for the tools on the site. Feel free to email directly.

  • Stefan

    Warning: Invalid argument supplied for foreach() in /home/httpd/httpdocs/user2/updateDB.php on line 12

    ??? Help

  • Thanks so much for this! It works perfectly.

  • Greg

    I am using an Ordered List and in Chrome and Firefox, things works fine (i.e. if I drag #1 to the #3 spot, all of the list #s update properly).

    But in IE, when I drag one to a new position, the OL number disappears and I can’t move that one anymore.

    Anyone know why this isn’t working in IE?

  • Thanks, it works great! 🙂

  • I have now even got it working with sub-links. For Internet Explorer (IE), however, you need the newest versions of jQuery and jQuery-UI for that.

  • Deepu Das

    Thanks, works like charm 🙂

  • steven

    I can’t get it work on iphone?

  • Hello, I’m Brazilian, of Rio de Janeiro.
    Very good code, I would like to know how the user to add your own text, I mean, he goes and adds the index to a new text by the order.

    aguardo sua resposta, muito obrigado

  • Thank’s for this tutorial .. I have been searching for this method for my project. 🙂

  • kamabhavik

    hey ..can any one give me code for drag and drop examples..in which i can add drag object dynamically in to drop area…and i want olso a drop area dat i can add dynamic..please ..please..can anyone help me out….thanks in advance

  • fik

    Not working in IE 9. Explorer 7,8 are Ok.

  • Sunil

    Hey Fik, Just add
    jquery.ui.widget.js,
    js/jquery.ui.mouse.js,
    js/jquery.ui.draggable.js,
    js/jquery.ui.sortable.js
    to you code and remove jquery-ui-1.7.1.custom.min

    and will work on all browser (like ie9 and safari)

  • priyanka jagtap

    I need an activity where the user can re-arrange a sentence to the correct order.

    The page needs to load dynamically, and pull the sentences from an external XML file.

    For example if the sentence is “The cat chased the mouse through the door and into the paddock.” The XML file would look like this

    The cat chased
    the mouse
    through the door
    and into the paddock

    The html file needs to pull these lines, shuffle them, and show the user if they have the correct order. Example:
    the mouse
    and the paddock
    the cat chased
    through the door

    The user needs to be able to drag and drop the lines to put them in order.

    Once the lines are in the correct order, a box appears which says “congratulations” and then the next question is loaded without a page load. This would go on to in the XML file

  • @priyanka,

    That is completely a unique example but you can get inspired from this article regarding the drag ‘n’ drop part.

  • Chris

    For Iphone/Ipad/touchscreen:
    The code doesn’t work “as is” for touchscreen “drag and drop” interfaces.
    After quite a bit of searching, I found an amazingly simple way to fix that, so this now works on iphone/ipad touchscreen interfaces:
    http://touchpunch.furf.com/
    Since the code for the drag and drop already uses jquery, you are already most of the way finished!
    That’s it! Really! add one or two js files to your site, call those files in tags, and this drag and drop works on iphones! Dang cool!

  • Frazer

    How you present this information is brilliant for a budding front end web dev – I truly wish more people presented the breakdown so well (like taking the time to screenshot a 3col DB). What seems trivial to those who know is a block on allowing those who don’t to learn.

  • Mike

    Sadly, this does not appear to work with IE9. Is there a fix for this?

  • This is a beautiful piece of work. Thank you. I have a movie web site, and putting the actor(ess) and crew into the movies is annoying when you missed one or put it in the wrong order. But now with this code, I can go back and rearrange it to suit. This is so simple and small but powerful.

    Thank you.

  • Venkatesh

    When i am editing in the order from 3241 to 3421. In the arrays are displaying in the order 3421, but in the database it had showed 4312. What is the problem in the swapping process. I have download it and worked out in my localhost. Is there any other solution is possible. Not only this orderwise. So many orders are not correctly swapping. 1 Answer= 10 times happiness to achieve…

  • @Venkatesh,

    Te ordering is made according to the recordListingID field in the db and the items in the db should be matching their order with the web interface.

  • This is really awesome, thank you so much! I hope you’re happy to see that people still find and use this code several years after you wrote the article! 😀

  • VN

    Thank you for posting this. I was trying for a long time to implement your code with this handy jquery multiaccordion:

    http://dl.dropbox.com/u/24708866/labs/jquery-multi-open-accordion/index.html

    but I didn’t manage to do it so far.

    Do you think it is doable? It could be really useful for many people if this two scripts work together.

  • @VN,

    Just give it a try by adding drag to the slider. If it can be dragged, than why not..

  • Anonymous

    Perfect! Very good, thanks!!!

  • Mats

    Cant make this work in Explorer.
    I tryed the below but I’m not sure I did correct

    //
    Sunil
    April 21st, 2012 at 9:18 pm
    Hey Fik, Just add
    jquery.ui.widget.js,
    js/jquery.ui.mouse.js,
    js/jquery.ui.draggable.js,
    js/jquery.ui.sortable.js
    to you code and remove jquery-ui-1.7.1.custom.min

    and will work on all browser (like ie9 and safari)
    //

  • ouija

    Thank you for your excellent code!

    I did make a slight modification to stop it from updating the database using multiple queries, and instead have it saving updates to all records using a single query.

    To do so, simply by replacing the “if ($action == “updateRecordsListings”) { ….. }” function of your code with the following:

    if ($action == “updateRecordsListings”) {

    $strVals = array();
    foreach($updateRecordsArray as $k=>$v) {
    $strVals[] = ‘WHEN ‘.(int)$v.’ THEN ‘.((int)$k+1).PHP_EOL;
    }
    $query = “UPDATE records SET recordListingID = CASE recordID “.join($strVals).” ELSE recordListingID END”;
    mysql_query($query) or die(‘Error, insert query failed’);

    echo ”;
    print_r($updateRecordsArray);
    echo ”;
    echo ‘If you refresh the page, you will see that records will stay just as you modified.’;
    }

    Hope this helps others!

  • ouija

    Ughh, this comment form replaced some of the values in that code, but that should give you the idea 🙂

  • Maxine Toledo

    This is great.

    Is it possible to have a button save which when click, saves to database rather than dragging and save??

    please reply. need asap. thanks!

  • @Maxine,

    With some custom coding you can easily do that.

    Just keep the modified array inside a hidden text element or store it in a session and, when the button is saved, execute the query.

    Simply, you should get your hands a little dirty 🙂

  • Maxine Toledo

    @Umut Thanks, I read comment of @Mentor and I hope I can do the same he did.

  • Aleksandar

    Hello,
    Can you please update this code to works with newer PHP?

  • lzxz1234

    The demo can’t run in ie10?My iexplore version is 10.0.9200.16438。

  • I like the demo but is there anyway to use drag and brop for submenus as well.
    Thanks

  • Edwin Winifred

    Hi it was really a nice post, initially the drag and drop did not work in ie9, seeing the earlier posts that to install and use the jQuery UI 1.8.15 it started working for.

    Thanks for the post !!

  • Doesn’t work in IE10 unless the compatibility mode icon is clicked. But, then, half the perfectly good stuff out there doesn’t work in IE10.

  • Very helpful post.. Thanks

  • Daniel Cuervo

    Hello!!! where can I find another server of the project for edit? the link dont open in my browser.

  • Mike Schmidt

    Any chance you can post the Download again somewhere. The link doesn’t seem to be working. Thanks!!!

  • Javad Hajiani

    this Download Link And Demo Not Working , Can You Help Me ?

Search