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

by Vincy. Last modified on July 3rd, 2023.

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, drag and drop is the best option.

There are several plugins for gallery display with a reordering feature. We will implement this example with custom code using jQuery UI libraries.

In the Trello like project management example, we have seen how to reorder task cards based on their 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.

View Demo

I highly recommend you check that article to witness a seasoned drag-and-drop implementation.

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

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 shown in this gallery. The PHP code for fetching database results and iterating the resultant photo arrays is 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 the drag and drop feature to change the photo position in the gallery UI. We can turn the gallery photo elements sortable by calling the jQuery UI sortable() method with the appropriate reference.

While sorting, the drop index is stored in a variable. This value will be used to construct the image id array based on conditions 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 must 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 is received in this file and iterated to execute the 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;

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Change Order of Images in Photo Gallery with Drag and Drop using PHP AJAX”

  • Tom says:

    Thank you! Very clear and useful tutorial!

  • Piers Storey says:

    Fantastic article. Many thanks for taking the time to write it.

  • johnd says:

    Demo does not save the new order – refresh the page and they go back to old order

    • Vincy says:

      I am not saving the state in database for demo. But you can check it out by running the code on your system. Full code is available for download free.

  • Chris Johnson says:

    Hello! Thanks so much for this code as I’m a little inexperienced with PHP & jQuery. This is almost exactly what I was looking for.

    May I ask you a question? I think I can adapt this to what I’m doing. I have written mysql stored procedures that will initially present 6 randomly stored pictures to a viewer, then I would like for the viewer to set them in the order of their choice (just like your scripts!) & submit them to another stored procedure that will record the “ranking”, and present them with another 6 pictures, and repeat the process. My question is this: Does your code post back to the table the newly ordered pictures? If so, I think I can retool it to just log another record of the selected order instead of overwriting the current record, yes?

    Thanks again!

    • Vincy says:

      Hi Chris,

      This code is not 100% feature complete. This is just a starting point, and needs to be enhanced for an appropriate project level use.

  • Bhanuka says:

    Hi, I have tried this project. Sometimes this does not work as expected. Sometimes the images are ordered in the correct way. But sometimes images are not shown in order. The drag-and-drop works well. But after submitting, the order of the images changes most of the times. Please let me know if there is a solution. Thanks.

    • Vincy says:

      Hi Bhanuka,

      When you say ‘sometimes’, can you give me more information on that. Also show me your code to help you out.

  • H Shirzad says:

    updateed order gives multiple image with same order no

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page