Skip to Content
jquery drag and drop save to database CodeIgniter
codeigniter code / September 11, 2021

The draggable feature comes in handy when incorporating Drag and Drop capabilities into a web application. jQuery UI makes enabling the draggable feature on any DOM element simple. The items can be dragged and dropped using the mouse with the jQuery draggable capability. You may leverage the drag and drop functionality of the jQuery UI draggable feature to dynamically reorganise the objects. The greatest approach for making the reorder list user-friendly is to use the drag and drop capability.

The order of the photographs in the listing should be maintained by the database if you want to control the order dynamically. In this article, we’ll teach you how to use CodeIgniter’s drag-and-drop capability to implement reordering functionality. To rearrange image order and store list order in the database, the example script will use the jQuery UI library and Ajax.

To integrate drag and drop reordering of pictures in CodeIgniter, the following functionality will be created.

List the photographs from the database on the web page.
To provide draggable capability on the DOM element, use the jQuery UI sortable() method.
Rearrange the photos by dragging and dropping them.
Using jQuery and Ajax, save the image order to the database.
List the images in the order that they appear on the page.

Take a look at the file structure of the CodeIgniter Drag & Drop Image Reorder application as a starting point.

├── 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/


Make a 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 fields.

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;

(Drag drop.php) is the controller.
The Drag Drop controller is in charge of picture listing and order updates.

__construct() – Loads the Image model, which aids in the retrieval and updating of image file information in the database.
index() – Using the Image model’s getRows() method, fetch all images from the database.
Data from the images is passed to the view.
orderUpdate() – Returns the image IDs from an AJAX POST request.
The update() method of the Image model can be used to change the image order 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 
$this->load->view('drag_drop/index', $data); 
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; 

Modeling (Image.php)
The database operations are handled by the Image model (fetch and update).

__construct() – Define the name of the table that will hold the image data.
getRows() – Using the image order, fetch the file’s data from the database.
update() — Use the update() function of the CodeIgniter Query Builder Class to update the image order in the database.

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 = ''){ 
$this->db->order_by('img_order', 'asc'); 
$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){ 
if(!array_key_exists('modified', $data)){ 
$data['modified'] = date("Y-m-d H:i:s"); 
$update = $this->db->update($this->tableName, $data, array('id' => $id)); 
return $update?true:false; 

(drag drop/index.php)

is a page that you can look at.
jQuery and the jQuery UI library should be included.

<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 jQuery UI Draggable and Sortable capabilities can be enabled with the JavaScript code below.

The sortable() method should be applied to the picture elements.
POST the picture order to the server-side script (drag drop/orderUpdate) using Ajax on the Save Order request to update the image order in the database.

Reload the page with the new listing order after you receive 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;

Initially, all images are fetched from the Drag Drop controller and listed in the img order field of the images table in the order indicated in the img order field.

When you click the reorder link, the drag-and-drop capability is activated, allowing you to sort the image list.
Drag and drop allows the user to modify the arrangement of the photos.
When you click the Save Reorder button, the order of the photos is communicated to the Drag Drop controller’s orderUpdate() method via 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 } } ?>


PHPCODE © 2023