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

0 42

Drag and Drop feature makes web page user-friendly and provides a nice User Interface for the web application. jQuery UI provides an easy way to add draggable functionality on DOM element. This tutorial shows you the uses of jQuery drag and drop feature to sort the list elements.

If we want to control the display order of images in the list, 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. Here we’ll explain how to add jQuery drag and drop feature to rearrange images order and save images display order to the MySQL database. You can use this functionality for managing images gallery, managing users list or any other useful place.

Our example script helps to implement dynamic drag and drop reorder images using jQuery, Ajax, PHP and MySQL. Using our scripts you can also implement the drag and drop reorder list, rows or sorting elements.

Before you begin, take a look at the folder and files structure to build drag and drop reorder images functionality using jQuery, Ajax, PHP and MySQL.

  • db.php
  • orderUpdate.php
  • index.php
  • style.css
  • images/

Database Table Creation

To store uploaded images information with display order, a table is required in MySQL database. The following SQL creates images table with some basic required fields in the database.

DB Class (db.php)

The DB class handles all the database related works. Specify your database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName). The DB class contains two methods to fetch and update images data.

  • getRows() function fetch the images data from the database.
  • updateOrder() function updates list order of the images.

Update Images Order (orderUpdate.php)

The order_update.php file receive the current images order from the index.php through Ajax. The images IDs string breaks into array and pass to the DB class to update the images reorder.

Reorder Images with Drag and Drop (index.php)

The index.php file display the images and allow the user to reorder images by drag and drop.
JavaScript
Include the jQuery and jQuery UI library.

The following jQuery codes are used to enable the jQuery sortable() features and implement the drag & drop functionality. When save request is submitted by the user, current images order send to the orderUpdate.php file using Ajax for update images order.

PHP & HTML
Initially, all the images are listed from the database using PHP and DB class. Once the reorder link is clicked, drag & drop feature is enabled for reorder.

style.css

This file contains some CSS code, which is used to styling the image gallery and links.

 

You might also like More from author

Leave A Reply

Your email address will not be published.