How to Drag and Drop Reorder Images in CodeIgniter

How to Drag and Drop Reorder Images in CodeIgniter

How to Drag and Drop Reorder Images in CodeIgniter

0 Sales


Draggable is a highly handy tool for integrating Drag and Drop capability into a web application. jQuery UI makes it simple to activate the draggable property on any DOM element. Elements may be moved by dragging and dropping them with the mouse when utilising the jQuery draggable capability. Using the jQuery UI draggable feature, you may reorganise the items dynamically by dragging and dropping them. To make the ordering list more user-friendly, use the drag and drop functionality.

If you wish to control the picture listing order dynamically, the database should keep track of it. In this article, we'll teach you how to leverage CodeIgniter's drag and drop tool to add rearrange images capability. The jQuery UI framework and Ajax will be used in the sample script to rearrange picture order and store list order in the database.

The following features will be added to CodeIgniter to allow for drag-and-drop picture reordering.

- Retrieve the photos first from data and stores those on the web site.

- To provide draggable capability on the DOM element, just use jQuery UI sortable() technique.

- Drag and drop photos to re-arrange their order.

- Using jQuery and Ajax, save the picture order to the database.

- List the photos in the order specified.

Before you begin, examine the data format of the demo CodeIgniter Drag & Drop Image Reorder application.

├── application/
│   ├── controllers/
│   │   └── Drag_drop.php
│   ├── models/
│   │   └── Image.php
│   └── views/
│       └── drag_drop/
│           └── index.php
└── assets/
    ├── js/
    │   │── jquery.min.js
    │   └── jquery-ui.min.js
    ├── css/
    │   └── style.css
    └── images/


Create Database Table

A table in the database is required to contain the file metadata and image order. In the MySQL database, the following SQL creates a pictures table with some basic columns.

CREATE TABLE `images` (
 `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,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


Controller (Drag_drop.php)


The Drag Drop controller is in charge of picture listing and order updating.

1. __construct() –

     - Loads the Image model, which is used to obtain and update image file information in the database.

2. index() –

     - Using the Image model's getRows() function, retrieve all images from the database.

     - Data from photos should be sent to the view.

3. orderUpdate() –

     - Get the image IDs from the AJAX POST request.

     - Use the Image model's update() function to change the order of images in the database.


defined('BASEPATH') OR exit('No direct script access allowed'); 
class Drag_Drop extends CI_Controller { 
    function  __construct() { 
        // Load file model 
    function index(){ 
        $data = array(); 
        // Get images data from the database 
        $data['images'] = $this->image->getRows(); 
        // Pass the images data to view 
    function orderUpdate(){ 
        // Get id of the images 
        $ids $this->input->post('ids'); 
            // Generate ids array 
            $idArray explode(","$ids); 
            $count 1; 
            foreach ($idArray as $id){ 
                // Update image order by id 
                $data = array('img_order' => $count); 
                $update $this->image->update($data$id); 
                $count ++;     
        return true; 


Model (Image.php)


The Image design is in charge of database operations (update and fetch).

1. __construct() –

The name of the table that will hold the image data.

2. getRows() –

Retrieve the information from the database for the file depending on the graphic order.

3. update() —

Use the update() method of the CodeIgniter Query Builder Class to keep updating the graphic order in the data.

defined('BASEPATH') OR exit('No direct script access allowed'); 
class Image extends CI_Model{ 
    function __construct() { 
        $this->tableName 'images'; 
     * Fetch files data from the database 
     * @param id returns a single record if specified, otherwise all records 
    public function getRows($id ''){ 
        $query $this->db->get(); 
        return ($query->num_rows() > 0)?$query->result_array():false; 
     * Update file data into the database 
     * @param array the data for inserting into the table 
     * @param int the row id 
    public function update($data = array(), $id){ 
            $data['modified'] = date("Y-m-d H:i:s"); 
        $update $this->db->update($this->tableName$data, array('id' => $id)); 
        return $update?true:false; 


View (drag_drop/index.php)


Include the jQuery and jQuery UI library.

<script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery-ui.min.js"></script>


The JavaScript code below is used to activate basic UI Draggable and Sortable capabilities.

- To the picture elements, add the sortable() function.

- Upload the picture order to the server-side script (drag drop/orderUpdate) via Ajax on the Save Order request to change the graphic order in the database.

- Refresh the tab with the altered listing order after receiving the response.


        $("ul.reorder-photos-list").sortable({ tolerance: 'pointer' });
        $('.reorder_link').html('save reordering');
        $("#saveReorder").click(function( e ){
            if( !$("#saveReorder i").length ){
                $(this).html('').prepend('<img src="<?php echo base_url('assets/images/refresh-animated.gif'); ?>"/>');
                $("#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() {
                    type: "POST",
                    url: "<?php echo base_url('drag_drop/orderUpdate'); ?>",
                    data: {ids: " " + h + ""},
                    success: function(){
                return false;


Typically, all pictures are collected from the Drag Drop command and displayed in the order indicated in the images table's img order property.

- When the reordering link is clicked, the drag-and-drop feature is activated, allowing you to sort the picture list.

- The user may modify the arrangement of the photographs by dragging and dropping them.

- When you click the Save Reorder button, the picture order is given to the orderUpdate() method of the Drag Drop controller through jQuery Ajax, which updates the list order in the database.


<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">
        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="<?php echo base_url('assets/images/'.$row["file_name"]); ?>"/>
    <?php } } ?>




You can use it for personal or commercial projects. You can't resell it partially or in this form.


Create Date : Jan 21, 2022

Updated Date : Jan 23, 2022


Comments : 0

Downloads : 0