Drag and Drop Reorder Images using jQuery, Ajax, PHP & MySQL

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/

Create Database Table

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;

DB Class (DB.class.php)

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.

  • getRows() function retrieve the images data from the database.
  • updateOrder() function update list order of the images.
<?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; 
    } 
}

Reorder Images with Drag and Drop (index.php)

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.

  • When the save request is submitted, current images order send to the orderUpdate.php file via Ajax to update the images order in the database.
  • After receiving the response from Ajax request, the page will be reloaded.
<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.

  • Once the reorder link is clicked, drag & drop feature is enabled to reorder the images.
  • The user can change the position of the images by drag&drop.
  • On clicking the Save Reorder button, the images order is sent to the server-side script (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>

Update Images Order (orderUpdate.php)

The orderUpdate.php file is called by the Ajax request and receive the current images order from the list page (index.php) through Ajax.

  • Retrieve the images IDs using PHP $_POST method.
  • Convert the images IDs string to array format.
  • Save the images order in the database using updateOrder() method of DB class.
<?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

Conclusion

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

23 Comments

  1. Matheus Afonso Said...
  2. Mahesh Said...
  3. Shawry Mihawk Said...
  4. Ishaque Said...
  5. John Said...
  6. Eduardo Correia Said...
  7. Scyfox Said...
  8. Jeff Said...
  9. Raivindra Yadav Said...
  10. Sorabh Said...
  11. Gianluca Said...
  12. Sackbut Said...
  13. Eric Pieters Said...
  14. Bessie Said...
  15. Sven Said...
  16. Marilyn Said...
  17. Haley Said...
  18. Bradley Said...
  19. Cindy Said...
  20. Santhosh Kumar Said...
  21. Samaralayden Said...
  22. VincentusaH Said...
  23. Matt Said...

Leave a reply

keyboard_double_arrow_up