Drag and Drop feature makes the web page user-friendly and provides a nice user interface for the web application. Using jQuery and jQuery UI library, the drag&drop functionality can be implemented easily. The jQuery UI provides an easy way to add draggable functionality to the DOM element. This tutorial shows you the uses of the jQuery drag-and-drop feature to sort the list elements dynamically with the database.
If you want to control the display order of images in the list dynamically, image order needs to be stored in the database. In this tutorial, we’ll provide a more interactive way to implement the images reorder functionality using jQuery and PHP. The example script demonstrates how to add jQuery drag and drop feature to rearrange images order and save images display order in the database using PHP and MySQL. The Drag and Drop Reorder functionality is very useful for managing images gallery, users list, and other dynamic content lists.
The example code helps to implement dynamic drag and drop reorder images using jQuery, Ajax, PHP, and MySQL. This sample code also can be used to implement the drag and drop reorder the list, rows, or sorting elements.
Before getting started, take a look at the files structure to build drag and drop reorder images functionality using jQuery, Ajax, PHP, and MySQL.
dragdrop_reorder_images/ ├── index.php ├── orderUpdate.php ├── DB.class.php ├── js/ │ ├── jquery.min.js │ └── jquery-ui.min.js ├── css/ │ └── style.css └── images/
To store images and their display order, a table needs to be created in the database. The following SQL creates an images
table with some basic required fields in the MySQL database.
CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`img_order` int(5) NOT NULL DEFAULT '0',
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The DB class controls all the database related works (connect, fetch and update records). Specify the database host ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your MySQL database credentials.
The DB class has two methods to fetch and update images data.
<?php class DB{ // Database configuration private $dbHost = "localhost"; private $dbUsername = "root"; private $dbPassword = "root"; private $dbName = "codexworld"; private $imgTbl = 'images'; function __construct(){ if(!isset($this->db)){ // Connect to the database $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName); if($conn->connect_error){ die("Failed to connect with MySQL: " . $conn->connect_error); }else{ $this->db = $conn; } } } /* * Get rows from images table */ function getRows(){ $query = $this->db->query("SELECT * FROM ".$this->imgTbl." ORDER BY img_order ASC"); if($query->num_rows > 0){ while($row = $query->fetch_assoc()){ $result[] = $row; } }else{ $result = FALSE; } return $result; } /* * Update image order */ function updateOrder($id_array){ $count = 1; foreach ($id_array as $id){ $update = $this->db->query("UPDATE ".$this->imgTbl." SET img_order = $count, modified = NOW() WHERE id = $id"); $count ++; } return TRUE; } }
The index.php
file displays the images on the web page and allows the user to reorder images by drag and drop.
JavaScript Code (jQuery and Ajax):
The drag&drop reorder script uses jQuery and Ajax, so, include the jQuery and jQuery UI library to use Ajax and Draggable functionality.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.3/jquery-ui.min.js"></script>
The following jQuery code is used to enable the jQuery UI Draggable & Sortable features and implement the drag & drop functionality.
orderUpdate.php
file via Ajax to update the images order in the database.<script type="text/javascript">
$(document).ready(function(){
$('.reorder_link').on('click',function(){
$("ul.reorder-photos-list").sortable({ tolerance: 'pointer' });
$('.reorder_link').html('save reordering');
$('.reorder_link').attr("id","saveReorder");
$('#reorderHelper').slideDown('slow');
$('.image_link').attr("href","javascript:void(0);");
$('.image_link').css("cursor","move");
$("#saveReorder").click(function( e ){
if( !$("#saveReorder i").length ){
$(this).html('').prepend('<img src="images/refresh-animated.gif"/>');
$("ul.reorder-photos-list").sortable('destroy');
$("#reorderHelper").html("Reordering Photos - This could take a moment. Please don't navigate away from this page.").removeClass('light_box').addClass('notice notice_error');
var h = [];
$("ul.reorder-photos-list li").each(function() {
h.push($(this).attr('id').substr(9));
});
$.ajax({
type: "POST",
url: "orderUpdate.php",
data: {ids: " " + h + ""},
success: function(){
window.location.reload();
}
});
return false;
}
e.preventDefault();
});
});
});
</script>
PHP & HTML Code:
Initially, all the images are fetched from the database and listed as per the order specified in the img_order
field of images table using PHP and DB class.
orderUpdate.php
) using jQuery Ajax for updating list order in the database.<div class="container">
<a href="javascript:void(0);" class="reorder_link" id="saveReorder">reorder photos</a>
<div id="reorderHelper" class="light_box" style="display:none;">1. Drag photos to reorder.<br>2. Click 'Save Reordering' when finished.</div>
<div class="gallery">
<ul class="reorder_ul reorder-photos-list">
<?php
// Include and create instance of DB class
require_once 'DB.class.php';
$db = new DB();
// Fetch all images from database
$images = $db->getRows();
if(!empty($images)){
foreach($images as $row){
?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<a href="javascript:void(0);" style="float:none;" class="image_link">
<img src="images/<?php echo $row['file_name']; ?>" alt="">
</a>
</li>
<?php } } ?>
</ul>
</div>
</div>
The orderUpdate.php
file is called by the Ajax request and receive the current images order from the list page (index.php
) through Ajax.
<?php // Include and create instance of DB class require_once 'DB.class.php'; $db = new DB(); // Get images id and generate ids array $idArray = explode(",", $_POST['ids']); // Update images order $db->updateOrder($idArray); ?>
Drag and Drop File Upload using DropzoneJS and PHP
Drag and drop images order functionality is very useful for image management section where you want to allow the user to set the order of the images. Not only the images list but also it can be used for many other purposes. Our example script will help you to add drag and drop reorder functionality to the element list using PHP and MySQL. Also, you can easily enhance our Drag & Drop Reorder script functionality as per your needs.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Great tutorial friend, it helped me a lot to solve a problem of a system !!! Thank you very much!!!
This tutorial awesome .
You save my day..may god bless ur life n help u go through hard time..
Brilliant effort!
Very helpful and the code is clean and solid, thanks!
The best ever! Thanks!
Hello.
Can I submit the ajax call to the same page to avoid having an extra page?
Thanks in advance
How do I get this to work on iphone or ipad? There appears to be touchscreen functionality missing.
thank you sir,please submit more and more
Can anybody tell me that what is the use of this line?
if( !$(“#save_reorder i”).length )
Ciao
It’s a good script!
Is there a solution for drag-drop on tablet? I tried using android but doesn’t work. Is drag drop a problem for all touch screen?
Thanks
G.
Well done and thanks you – this worked “straight out of the box”. I’ll be incorporating it into a site soon
Can anybody email me what the following line does in the script?
I cannot find the reason it is there.
if( !$(“#save_reorder i”).length )
Saved as a favorite, I like your blog!
Awesome! Its in fact awesome piece of writing, I have got much clear
idea concerning from this post.
Hi, constantly i used to check webpage posts here early in the dawn, since i like to find out more and more.
Very nice article, just what I wanted to find.
whoah this weblog is magnificent i love studying your articles.
Stay up the good work! You already know, lots of individuals are hunting
round for this information, you can aid them greatly.
I’m not that much of a online reader to be
honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back later
on. Many thanks
Hi .. I check your blogs daily. Your writing style
is awesome and excellent , keep up the good work!
bookmarked!!, I love your site!
Nice tutorial, please continue posting.
Awesome tutorial. Thank you !