Dynamic Drag and Drop with jQuery and PHP

Dynamic Drag and Drop with jQuery and PHP

A new tutorial about Dynamic Drag and Drop With jQuery and PHP is available. Need to order your items quickly and easily ? so read this tutorial step by step. A basic knowledge about PHP and jQuery is required.

Download source code

This tutorial is based on the jqueryui.

1. Demonstration

2. Structure

/css : contain the CSS files
/js : contain the JavaScript files
/images : contain all images

3.Database

Create a new database named drag_and_drop, and import the SQL script in the main folder, or copy/paste the script bellow:

--
-- Table structure for table `items`
--

CREATE TABLE IF NOT EXISTS `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `photo` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `item_order` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ;

--
-- Dumping data for table `items`
--

INSERT INTO `items` (`id`, `photo`, `title`, `description`, `item_order`) VALUES
(1, 'images/demo_1.jpg', 'item 1', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 1),
(2, 'images/demo_2.jpg', 'item 2', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 2),
(3, 'images/demo_3.jpg', 'item 3', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 3),
(4, 'images/demo_4.jpg', 'item 4', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 4),
(5, 'images/demo_5.jpg', 'item 5', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 5);

4. Files

index.php

This is the main file, it will be displayed on the first view. It displays a list of items with photo, title and a small description. This items are loaded from the database.

<?php
// including the config file
include('config.php');
$pdo = connect();
// select all items ordered by item_order
$sql = 'SELECT * FROM items ORDER BY item_order ASC';
$query = $pdo->prepare($sql);
$query->execute();
$list = $query->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drag and Drop using jQuery and Ajax</title>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>

<body>
    <div class="container">
        <div class="header">
            <img src="images/BeWebDeveloper.png" alt="BeWebDeveloper" />
        </div><!-- header -->
        <h1 class="main_title">Drag and Drop using jQuery and Ajax</h1>
        <div class="content">

        <ul id="sortable">
            <?php
            foreach ($list as $rs) {
            ?>
            <li id="<?php echo $rs['id']; ?>">
                <span></span>
                <img src="<?php echo $rs['photo']; ?>">
                <div><h2><?php echo $rs['title']; ?></h2><?php echo $rs['description']; ?></div>
            </li>
            <?php
            }
            ?>
        </ul>
        </div><!-- content -->    
        <div class="footer">
            Powered by <a href="http://www.bewebdeveloper.com/">bewebdeveloper.com</a>
        </div><!-- footer -->
    </div><!-- container -->
</body>
</html>

config.php

This is the config file. It contains a single function for connection to the database using PDO.

<?php
// PDO connect *********
function connect() {
	$host = 'localhost';
	$db_name = 'drag_and_drop';
	$db_user = 'root';
	$db_password = '';
    return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
?>

set_order.php

This file will be executed after any drag and drop operation. It will change dynamically the order in the database.

<?php
// including the config file
include('config.php');
$pdo = connect();

// get the list of items id separated by cama (,)
$list_order = $_POST['list_order'];
// convert the string list to an array
$list = explode(',' , $list_order);
$i = 1 ;
foreach($list as $id) {
	try {
	    $sql  = 'UPDATE items SET item_order = :item_order WHERE id = :id' ;
		$query = $pdo->prepare($sql);
		$query->bindParam(':item_order', $i, PDO::PARAM_INT);
		$query->bindParam(':id', $id, PDO::PARAM_INT);
		$query->execute();
	} catch (PDOException $e) {
		echo 'PDOException : '.  $e->getMessage();
	}
	$i++ ;
}
?>

script.js

This is the JavaScript file. It contain a single instantiation for the sortable object.

$(function() {
    $('#sortable').sortable({
        axis: 'y',
        opacity: 0.7,
        handle: 'span',
        update: function(event, ui) {
            var list_sortable = $(this).sortable('toArray').toString();
    		// change order in the database using Ajax
            $.ajax({
                url: 'set_order.php',
                type: 'POST',
                data: {list_order:list_sortable},
                success: function(data) {
                    //finished
                }
            });
        }
    }); // fin sortable
});

style.css

This is the CSS file, it contain the design styles

* {
	margin: 0;
	padding: 0;
}
body {
	padding: 10px;
	background: #eaeaea;
	text-align: center;
	font-family: arial;
	font-size: 12px;
	color: #333333;
}
.container {
	width: 1000px;
	height: auto;
	background: #ffffff;
	border: 1px solid #cccccc;
	border-radius: 10px;
	margin: auto;
	text-align: left;
}
.header {
	padding: 10px;
}
.main_title {
	background: #cccccc;
	color: #ffffff;
	padding: 10px;
	font-size: 20px;
	line-height: 20px;
}
.content {
	padding: 10px;
	min-height: 100px;
	text-align: center;
}
.footer {
	padding: 10px;
	text-align: right;
}
.footer a {
	color: #999999;
	text-decoration: none;
}
.footer a:hover {
	text-decoration: underline;
}
/* Sortable ******************/
#sortable { 
	list-style: none; 
	text-align: left; 
}
#sortable li { 
	margin: 0 0 10px 0;
	height: 75px; 
	background: #dbd9d9;
	border: 1px solid #999999;
	border-radius: 5px;
	color: #333333;
}
#sortable li span {
	background-color: #b4b3b3;
	background-image: url('../images/drag.png');
	background-repeat: no-repeat;
	background-position: center;
	width: 30px;
	height: 75px; 
	display: inline-block;
	float: left;
	cursor: move;
}
#sortable li img {
	height: 65px;
	border: 5px solid #cccccc;
	display: inline-block;
	float: left;
}
#sortable li div {
	padding: 5px;
}
#sortable li h2 {    
	font-size: 16px;
    line-height: 20px;
}
Drag and Drop, JavaScript, jQuery, PHP
comments powered by Disqus

Social Profiles

bewebdeveloper on facebook bewebdeveloper on twitter bewebdeveloper on google plus bewebdeveloper on vk bewebdeveloper on youtube bewebdeveloper on tumblr bewebdeveloper rss

Subscribe to our Newsletter

Facebook

Twitter

Google+

HTML Tutorials
CSS Tutorials

Advertising