Show additional user pictures with sliding animation on button click using jQuery, PHP and MySQL

I have a photo gallery where I show only 5 pictures at first. When someone clicks a button, I want the remaining photos to appear with a smooth sliding effect.

Right now my page loads just a few photos from the database. I need help figuring out how to make the other pictures show up when someone clicks a button. The new photos should slide down smoothly.

Here’s what I’m trying to do:

// Initial photo loading
$query = "SELECT photo_url FROM user_photos WHERE user_id = ? LIMIT 5";
$stmt = $pdo->prepare($query);
$stmt->execute([$userId]);
$photos = $stmt->fetchAll();

foreach($photos as $photo) {
    echo '<img src="' . $photo['photo_url'] . '" class="gallery-image">';
}
$('#load-more-btn').click(function() {
    // Need code here to load and slide down remaining photos
});

What’s the best way to fetch the extra images and animate them sliding down? Should I use AJAX to get the remaining photos from MySQL?

AJAX is definitely the way to go. I built something similar and hit performance issues loading everything upfront. Track which photos you’ve loaded so you don’t get duplicates.

For the backend, make an endpoint that takes an offset parameter. Something like SELECT photo_url FROM user_photos WHERE user_id = ? LIMIT 5 OFFSET ? - start offset at 5 for the second batch.

On the frontend, wrap your new images in a hidden container first, then use jQuery’s slideDown(). Set the container to display: none, append your fetched images, then call slideDown(). That’ll give you the smooth sliding animation.

Watch out for when there’s no more photos to load. I return an empty array and hide the load button when that happens. Also throw in a loading spinner during the AJAX request - users appreciate it.