How to Implement Drag-and-Drop Image Reordering in CodeIgniter

by Shailender K. 4 minute read 35 views

Implement drag-and-drop reordering in CodeIgniter using Bootstrap and jQuery. It improves user experience by updating image order perfectly via AJAX and database integration.

Key Points

  • Built using CodeIgniter 4.0 framework with PHP 7.4 for backend image order handling.
  • Frontend uses Bootstrap 5.3 and jQuery 3.7 to support drag-and-drop functionality.
  • The database table includes a sort_order column to store a predefined static order of image records.
Digittrix Blog Author Image

Web Developer

Shailender K.

3 min read

Passionate web developer with 3+ years of experience creating responsive and high-performing web applications.

image how logo of CodeIgniter, featuring a stylized flame symbol in orange, representing a PHP framework.

In the evolving landscape of website development services, creating interactive and user-friendly interfaces is crucial. One highly requested feature in custom web development is drag-and-drop functionality, particularly for reordering images or content elements dynamically. Whether you're developing an admin dashboard, content management system, or gallery, drag-and-drop reordering enhances usability and improves user experience.

In this guide, we’ll walk you through implementing drag-and-drop image reordering using CodeIgniter 4.0, Bootstrap 5.3, and jQuery 3.7. This feature can be an excellent addition for Front-end Developers and Backend Developers building responsive and dynamic web applications. Additionally, if you're planning to hire laravel developers or are already working with a PHP-based team, the same logic can be adapted to Laravel with ease.

Why Use Drag-and-Drop Reordering?

Custom web development isn’t just about looks—it’s about functionality that streamlines user interactions. With drag-and-drop image sorting:

  • Admins can easily organize content

  • Galleries and listings become more flexible

  • User interfaces feel more modern and intuitive

Whether you're part of a freelance dev team or a full-scale digital agency offering website development services, mastering this functionality is a major asset.

Step 1: Define Routes

To manage the drag-and-drop functionality and allow AJAX-based reordering, define the following routes in app/Config/Routes.php:

                                           $routes->get('drag_and_drop', 'UserController::drag_and_drop');      
   $routes->post('update-short-order', 'UserController::updateShortOrder');

                                        
                                    

The GET route loads the sortable table view. The POST route receives the updated image order from the AJAX call and updates the database accordingly. This structure supports scalable custom web development practices, allowing both Front-end Developers and Backend Developers to collaborate efficiently.

Step 2: Create Database Table

Create a 'users' table to store the image and user data. Here’s the recommended SQL schema:

                                        CREATE TABLE users (
    id INT(11) NOT NULL AUTO_INCREMENT,
    name VARCHAR(255) DEFAULT NULL,
    last_name VARCHAR(255) DEFAULT NULL,
    email VARCHAR(255) DEFAULT NULL,
    address TEXT DEFAULT NULL,
    phone VARCHAR(255) DEFAULT NULL,
    about TEXT DEFAULT NULL,
    image VARCHAR(255) DEFAULT NULL,
    img_url VARCHAR(255) DEFAULT NULL,
    sort_order INT(11) DEFAULT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE
    CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
         );
                                        
                                    

The sort_order field is used to control the sequence of records, making this structure optimal for dynamic content control systems often built in custom web development projects.

Step 3: Create Model

Create a model named UserModel to manage database interactions.

File: app/Models/UserModel.php

                                        <?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{    
    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    protected $table            = 'users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
        
    protected $allowedFields    = [
        'name',
        'last_name',
        'email',
        'address',
        'phone',
        'about',
        'Image',
  'sort_order',
        'img_url',
        'created_at', 
        'updated_at'
    ];

    protected $DBGroup = 'customDB';  // optional

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    
    protected $updatedField  = 'updated_at';
    protected $usePagination = true;

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++     
    
    public function getListData(){
        return $this->table('users')
        ->select('*')
        ->orderBy('sort_order', 'ASC')
        ->get()
        ->getResultArray();
    }
    
    public function updateShortOrder($id, $sortOrder) {
        $builder = $this->db->table('users');
        $builder->set('sort_order', $sortOrder);
        $builder->where('id', $id);
        $builder->update();

        if ($this->db->affectedRows() > 0) {
            return true;
        } else {
            return false;
        }
    }

}
                                        
                                    

This model ensures your Backend Developers have an efficient and clean method to manage the reordering logic.

Step 4: Create Controller

Create UserController to manage data flow and handle AJAX requests.

File: app/Controllers/UserController.php

                                         <?php

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\UserModel;

class UserController extends BaseController
{
    		protected $session;
    		protected $UserModel;

    		public function __construct() {   
        		$this->session = \Config\Services::session();            
        		$this->UserModel = new UserModel(); 
        		helper(['form', 'url']);
    		}
    
    		// -------- drag and drop ----------------
    		public function list_data(){
       		$query['users'] = $this->UserModel->getListData();
    	    		return view('index', $query);
    		}

    		public function updateShortOrder(){            
        		$orders = $this->request->getPost('order');
        		$res = true;

        		foreach($orders as $key => $value){
            		if (!$this->UserModel
                       ->updateShortOrder($value, $key)) {
                			$res = false;
            		}
        		}
        		echo $res;        
    		}   
}
                                        
                                    

This controller architecture is perfect for scalable solutions created by Backend Developers or full-stack teams in any professional website development service provider.

Step 5: Frontend View

The UI for drag-and-drop sorting is built using Bootstrap and jQuery.

File: app/Views/index.php

                                        <!doctype html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Drag and Drop - CodeIgniter</title>


        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        
    </head>

    <body>
        <div class="container py-5">
            <div class="row justify-content-center">
                <div class="col-lg-8">                
                    <div class="mb-4 text-center">
                        <h2 class="fw-bold">Drag and Drop Reorder data in CodeIgniter</h2>                    
                    </div>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover align-middle">
                            <thead class="table-dark">
                                <tr>
                                    <th scope="col">ID</th>
                                    <th scope="col">Name</th>
                                    <th scope="col">Last name</th>
                                </tr>
                            </thead>
                            <tbody id="sortable"> 
                                <?php if (!empty($users)): ?>
                                    <?php foreach ($users as $user): ?>
                                        <tr data-id="<?= $user['id']; ?>">
                                            <td>#<?= esc($user['id']); ?></td>
                                            <td><?= esc($user['name']); ?></td>
                                            <td><?= esc($user['last_name']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="2" class="text-center">No users found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>


        <!-- Script -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>    
        <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
        
        <script>
            $(function() {
                $("#sortable").sortable({
                    items: "tr",
                    cursor: "move",
                    update: function(event, ui) {
                        let order = $(this).sortable("toArray", { attribute: "data-id" });
                        console.log('sorting order', order);
                        $.ajax({
                            url: "<?= base_url('update-short-order'); ?>",
                            method: "POST",
                            data: {
                                order: order,
                            },
                            success: function(response) {
                                console.log('response', response);
                                alert('Updated successfully.');
                            },
                            error: function() {
                                alert('Error saving order.');
                            }
                        });
                    }
                });
                $("#sortable").disableSelection();
            });
        </script>
        
    </body>
</html>

                                        
                                    

This view integrates beautifully with the backend and provides a responsive interface for your clients. It's especially valuable for custom web development projects that require dynamic content organization.

Final Words

Integrating drag-and-drop image or data reordering in CodeIgniter 4.0 with Bootstrap and jQuery can significantly improve user experience. It's a crucial component of modern admin panels and content management systems, often requested by clients seeking high-quality website development services.

Whether you're a solo Front-end Developer or part of a team of Backend Developers, this implementation is straightforward and extendable. Businesses aiming for scalable custom web development often look to hire Laravel developers or PHP experts to incorporate such functionality seamlessly into their platforms.

Need expert help with drag-and-drop interfaces or want to hire Laravel developers for your next project? Get in touch with our team offering professional website development services that blend robust backends with intuitive frontends.

Tech Stack & Version

Frontend

  • HTML
  • CSS

 Backend

  • CodeIgniter 4.x
  • PHP 7.4+

Deployment

  • Apache

  • Nginx

img

©2025Digittrix Infotech Private Limited , All rights reserved.