Change Order of Images in Photo Gallery with Drag and Drop using PHP AJAX

Last modified on September 17th, 2018 by Vincy.

Drag and drop is a convenient UI feature for users when handling elements. In particular, while displaying images in a gallery and allowing the users to move around the images, then drag and drop is the best option. There are several plugins for gallery display with reordering feature. In this example, we will implement it with custom code using jQuery UI libraries.

Change-Order-of-Images-in-Photo-Gallery-with-Drag-and-Drop-using-PHP-AJAX

View Demo

In the Trello like project management example, we have seen how to reorder task cards based on its status. In this article, we will see how to apply the reordering feature to change the photo position in a gallery using PHP and jQuery. I highly recommend you to check that article to witness a seasoned drag and drop implementation.

The gallery images are dynamic from the database. Each photo card will be set with the draggable property to drag it to change its order. Once reordering is completed, the order will be updated in the database by clicking the Save button.

Code to Show Photo Gallery

This code contains HTML to display the gallery view to the user. The photos are fetched from the database and displayed in this gallery. The PHP code for fetching database results and iterating resultant photo array are embedded with the gallery view HTML.

<?php
require_once "db.php";
$sql = "SELECT * FROM tbl_images ORDER BY image_order ASC";
$result = $conn->query($sql);
$conn->close();
?>
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css" >
        <title>Change Order of Images in Photo Gallery with Drag and Drop using PHP AJAX</title>
    </head>
    <body>
        <div id="gallery">
        
        <div id="image-container">
        <h2>Change Order of Images in Photo Gallery with Drag and Drop using PHP AJAX</h2>
        <div id="txtresponse" > </div>
            <ul id="image-list" >
                <?php
                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {

                        $imageId = $row['id'];
                        $imageName = $row['image_name'];
                        $imagePath = $row['image_path'];

                        echo '<li id="image_' . $imageId . '" >
                        <img src="' . $imagePath . '" alt="' . $imageName . '"></li>';
                    }
                }
                ?>
            </ul>

        </div>            
        <div id="submit-container"> 
            <input type='button' class="btn-submit" value='Submit' id='submit' />
        </div>
        </div>
    </body>
</html>

Reorder with jQuery Drag and Drop

This script shows how to enable drag and drop feature to change the photo position in the gallery UI. By calling the jQuery UI sortable() method with the appropriate reference, we can turn the gallery photo elements sortable.

While sorting, the drop index is stored in a variable. This value will be used to construct the image id array based on condition to optimize the update process with the limited images.

For example, If the sorting is made between the first three images, then only these three records has to be updated instead of changing the entire image database.

After changing the image order, the Save button’s click event will send an AJAX request. In this request, a PHP code is called to update the changed order of multiple images in the DB.

<script src="vendor/jquery/jquery-3.2.1.min.js"></script>

<link rel="stylesheet" href="vendor/jquery/jquery-ui/jquery-ui.css">
<script src="vendor/jquery/jquery-ui/jquery-ui.js" type="text/javascript"></script>

<script>
    $(document).ready(function () {
        var dropIndex;
        $("#image-list").sortable({
            	update: function(event, ui) { 
            		dropIndex = ui.item.index();
            }
        });

        $('#submit').click(function (e) {
            var imageIdsArray = [];
            $('#image-list li').each(function (index) {
                if(index <= dropIndex) {
                    var id = $(this).attr('id');
                    var split_id = id.split("_");
                    imageIdsArray.push(split_id[1]);
                }
            });

            $.ajax({
                url: 'reorderUpdate.php',
                type: 'post',
                data: {imageIds: imageIdsArray},
                success: function (response) {
                   $("#txtresponse").css('display', 'inline-block'); 
                   $("#txtresponse").text(response);
                }
            });
            e.preventDefault();
        });
    });

</script>

PHP Code to Save Image Order in DataBase

This is the PHP code to save the image order in the database. This PHP file will be requested via AJAX by sending the image id references to be sorted. The array of image ids are received in this file and iterated to execute database update.

<?php
require_once "db.php";

$imageIdsArray = $_POST['imageIds'];

$count = 1;
foreach ($imageIdsArray as $id) {

    $sql = $conn->prepare("UPDATE tbl_images SET image_order=? WHERE id=?");
    $imageOrder = $count;
    $imageId = $id;

    $sql->bind_param("ii", $imageOrder, $imageId);
    if ($sql->execute()) {
        $response = 'Images order is updated';
    } else {
        $response = 'Problem in Changing the Image Order';
    }
    $count ++;
}

echo $response;
exit;
?>

Database Script

The gallery images are stored in the database table  tbl_images. The following database script shows the database table’s create statement and the data dump. Import this script to setup database to run this example in your PHP environment.

--
-- Table structure for table `tbl_images`
--

CREATE TABLE `tbl_images` (
  `id` int(11) NOT NULL,
  `image_name` varchar(200) NOT NULL,
  `image_path` varchar(50) NOT NULL,
  `image_order` int(2) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `tbl_images`
--

INSERT INTO `tbl_images` (`id`, `image_name`, `image_path`, `image_order`, `date`) VALUES
(2, 'Image6', 'images/image6.jpeg', 3, '2018-09-16 10:46:21'),
(3, 'Image1', 'images/image1.jpeg', 5, '2018-09-16 10:45:34'),
(4, 'Image2', 'images/image2.jpeg', 4, '2018-09-16 10:45:34'),
(5, 'Image3', 'images/image3.jpeg', 6, '2018-09-16 10:45:34'),
(6, 'Image4', 'images/image4.jpeg', 2, '2018-09-16 10:45:34'),
(9, 'Image5', 'images/image5.jpg', 1, '2018-09-16 10:45:34');

ALTER TABLE `tbl_images`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_images`
--
ALTER TABLE `tbl_images`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;

Photo gallery with drag and drop output

The photo gallery is shown below in the screenshot. In this screenshot a success message is shown to let the user know about the image order is changed in the database.

change-order-of-images-in-photo-gallery-with-drag-and-drop-using-php-ajax-output

View DemoDownload

↑ Back to Top

Share this Article