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.

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