Web20 University

Drag and Drop Images and Reorder Them Using jQuery, AJAX, PHP and MySQL

Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

In this tutorial, we’ll create a dynamic image reordering system using jQuery for drag-and-drop functionality, AJAX for seamless server communication, PHP for backend processing, and MySQL for data storage. We’ll use a list of fruits as our example.

Setting Up the Project

First, let’s set up our project structure and database.

Database Setup

Create a MySQL database named fruit_order and use this SQL script to create the necessary table:

CREATE TABLE fruits (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    image_url VARCHAR(255) NOT NULL,
    display_order INT NOT NULL
);

INSERT INTO fruits (name, image_url, display_order) VALUES
('Apple', 'images/apple.jpg', 1),
('Banana', 'images/banana.jpg', 2),
('Cherry', 'images/cherry.jpg', 3),
('Dragonfruit', 'images/dragonfruit.jpg', 4);

PHP Template

Create an index.php file with the following content:

<?php
$db = new mysqli('localhost', 'username', 'password', 'fruit_order');
$result = $db->query("SELECT * FROM fruits ORDER BY display_order");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fruit Reordering</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <style>
        #fruit-list { list-style-type: none; margin: 0; padding: 0; width: 60%; }
        #fruit-list li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
        #fruit-list li img { max-width: 50px; vertical-align: middle; margin-right: 10px; }
    </style>
</head>
<body>
    <h1>Reorder Fruits</h1>
    <ul id="fruit-list">
        <?php while ($row = $result->fetch_assoc()): ?>
            <li class="ui-state-default" data-id="<?= $row['id'] ?>">
                <img src="<?= $row['image_url'] ?>" alt="<?= $row['name'] ?>">
                <?= $row['name'] ?>
            </li>
        <?php endwhile; ?>
    </ul>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

jQuery Setup

Create a script.js file for our jQuery code:

$(function() {
    $("#fruit-list").sortable({
        update: function(event, ui) {
            var order = $(this).sortable('toArray', {attribute: 'data-id'});
            $.ajax({
                url: 'update_order.php',
                method: 'POST',
                data: {order: order},
                success: function(response) {
                    console.log('Order updated successfully');
                },
                error: function(xhr, status, error) {
                    console.error('Error updating order:', error);
                }
            });
        }
    });
});

Implementing Drag-and-Drop with jQuery

We’re using jQuery UI’s sortable() method to provide drag-and-drop functionality. We’ve already implemented this in our script.js file. The update callback is triggered when the user finishes dragging an item.

Sending Reordered Items via AJAX

In the update callback of our sortable() method, we’re using jQuery’s ajax() method to send the new order to the server. The toArray() method converts our sorted list into an array of item IDs.

Storing Results in MySQL via PHP

Create an update_order.php file to handle the AJAX request:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['order'])) {
    $db = new mysqli('localhost', 'username', 'password', 'fruit_order');
    
    $order = $_POST['order'];
    foreach ($order as $index => $id) {
        $index++; // Add 1 because array is 0-indexed
        $id = intval($id);
        $db->query("UPDATE fruits SET display_order = $index WHERE id = $id");
    }
    
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}

This script updates the display_order in the database based on the new order received from the AJAX request.

Conclusion

We’ve successfully implemented a drag-and-drop image reordering system using jQuery, AJAX, PHP, and MySQL. This system allows users to visually reorder items, with the new order being immediately saved to the database.

Key points to remember:

  1. jQuery UI’s sortable() method provides an easy way to implement drag-and-drop functionality.
  2. AJAX allows us to send the new order to the server without refreshing the page.
  3. PHP processes the AJAX request and updates the MySQL database.
  4. Proper error handling and user feedback are crucial for a smooth user experience.

This implementation can be easily adapted for various use cases, such as reorganizing photo galleries, prioritizing task lists, or customizing menu orders.

Get up to 65% Off Hosting with FREE SSL & FREE Domains!