Drag & Drop with PHP & jQuery

24 July 2009| 41 Comments| Print

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 whats 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.

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

demodownload

41 Comments

  • Roy

    Nice tutorial/howto, will try it tonight!

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

  • Ashley (author)

    @roy thanks fixed the typo ;)

  • Marc Falk

    Lovely! Just what I needed, thanks…

    Nice blog by the way ;)
    Cheers!

  • Brian Jørgensen

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

  • Felix

    Realy usefull!!, thanks for share your code.

  • Brian Jørgensen

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

  • Brian Jørgensen

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

  • Drag & Drop with PHP & jQuery | Papermashup.com « Netcrema - creme de la social news via digg + delicious + stumpleupon + reddit

    [...] Drag & Drop with PHP & jQuery | Papermashup.compapermashup.com [...]

  • Ashley (author)

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

  • Drag & Drop with PHP & jQuery | Papermashup.com

    [...] original post here: Drag & Drop with PHP & jQuery | Papermashup.com Share and [...]

  • Brian Jørgensen

    Awesome!

    Cool site btw – just subscribed to your rss !

  • Peter

    Nice post!! Thanks a lot

  • CSS Brigit | Drag & Drop with PHP & jQuery

    Drag & Drop with PHP & jQuery…

    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.

  • Twitted by UltraMegaTech

    [...] This post was Twitted by UltraMegaTech [...]

  • Drag & Drop with PHP & jQuery | Choose Daily

    [...] Drag & Drop with PHP & jQuery [...]

  • Sunny Singh

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

  • Ashley (author)

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

  • 網站製作學習誌 » [Web] 連結分享

    [...] Drag & Drop with PHP & jQuery [...]

  • LimeSpace – IT » Die Links der Woche – Urlaub im August

    [...] Wie macht man mit PHP + Jquery Drag and Drop -> Hier wird es erklärt [...]

  • 30+ Fresh & Amazing jQuery Plugins & Tutorials

    [...] 4. Drag & Drop With jQuery [...]

  • 30+ 新鲜惊奇的 jQuery 插件与教程

    [...] Drag & Drop With jQuery Web 应用程序的拖放功能提供了丰富的用户界面,了解如何使用 jQuery [...]

  • Alan

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

  • Anton

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

  • Ashley (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.

  • 30+ JQuery Plugins And Tutorials | oOrch Blog

    [...] 4.Drag & Drop With jQuery [...]

  • John S

    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 (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.

  • Enatom

    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 (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.

  • Enatom

    @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 (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

    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 (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

    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.

  • Ajmal

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

  • 30+ 新鲜惊奇的 jQuery 插件与教程 | 芒果

    [...] Drag & Drop With jQuery Web 应用程序的拖放功能提供了丰富的用户界面,了解如何使用 jQuery [...]

  • Indialike

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

  • trialanderror

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

    thanks,

  • trialanderror

    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.

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.