Dynamically Display Images in Bootstrap Modal with PHP and Ajax

If you want to make your web application more interactive, learn how to display dynamic images in a Bootstrap modal with PHP and Ajax. You can fetch data from a MySQL database and display it inside a Bootstrap modal popup without reloading the page. In this tutorial, we'll show you step-by-step how to use PHP Ajax Bootstrap Modal to display and manage dynamic content.

We will develop an application to demonstrate how to display an image in a Bootstrap modal from a database using PHP and Ajax dynamically.

A list of users along with the photos is displayed in an html table. By clicking on the photo thumbnail, a user can view the image in a modal, along with the name, as below:

PHP Ajax Bootstrap Modal Example

When a user clicks on a photo, user's ID is sent to a modal using a "data-id" attribute and then by running Ajax, details for the user (name, photo) can be displayed in the modal. Below is the code snippet of the link used for the photo:


<a href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#showImg" class="view" data-id="<?php echo $row['id']; ?>" >
<img class="photo" alt="Profile Photo" src="<?= $image_path.$row['image']; ?>" title="View Photo"/>
    </a>

Click to Watch YouTube Video

bootstrap modal image preview php ajax
Folders and Files

The folder structure and files we will be using:

dynamically display image in bootstrap modal

We created a folder named 'modal_photo' under 'xampp/htdocs'.

  1. Folder 'cfg' - In this folder, we have kept dbconnect.php which is used to connect to the MySQL database.
  2. Folder 'css' - Our custom stylesheet is in this folder
  3. Folder 'js' - In this folder, we have our custom JavaScript file which has Ajax script in it to display the photo in a modal.
  4. Folder 'uploads' - We have kept a few image files in this folder. This is supposed to be the folder where photos are uploaded. Since we are not showing image upload, we put some image files in this folder. These image names are also in the database table.
  5. index.php displays a list of users with name, email and photo thumbnail. The user has to click on a photo thumbnail to see larger size of it along with the name in a modal.
  6. get_user_details.php - It is the PHP program executed as an Ajax request to get details of the users from the database.

Create a MySQL table

We will be using a table named 'user_profile' in MySQL database. We will store user name, email and photo in this table. We will have some sample data in this table.

The columns are:

  1. id - It is the unique id of a user, primary key and auto incremented
  2. name - Name of the user
  3. email - Email of the user
  4. image - Image file name

user_profile.sql


CREATE TABLE `user_profile` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `image` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user_profile` (`id`, `name`, `email`, `image`) VALUES
(1, 'Avatar1', 'avatar1@test.com', 'avatar1.png'),
(2, 'Avatar2', 'avatar2@test.com', 'avatar2.png'),
(3, 'Avatar3', 'avatar3@test.com', 'avatar3.png');

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

ALTER TABLE `user_profile`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

Connect to MySQL database using PHP (dbconnect.php)

We will use the script below to connect to the database. We will keep this file under 'cfg' folder.

dbconnect.php


<?php
 $conn = new mysqli("localhost", "root", "", "test");

if ($conn->connect_error)
  die("DB Connection Error: " . $conn->connect_error);

We create a mysqli object with the below parameters.

  1. server - it is localhost.
  2. userid - we use the root user.
  3. password - no password for the root user.
  4. database name - we are using "test" database.

We will include dbconnect.php in other php programs so that we do not need to code again in another program. You can also read the read topic Connect PHP to MySQL with MySQLi and PDO Example Code.

Display a list of users (index.php)

We will display a list of users in an HTML table. Select the rows from the 'user_profile' table using a select statement, then fetch them in a loop and display them in an HTML table.

Below is the list of courses displayed by index.php

Fetch data in modal using Ajax PHP

Code to display users

We will select all users from the 'user_profile' table and display them in an html table along with the photo of the user. We will use Bootstrap 5, jQuery Ajax and Bootstrap modal. So the necessary libraries will be added. The code below is from index.php:

index.php


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Display image in a Bootstrap modal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="css/style.css">

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="js/modal.js"></script>
</head>

<body>
    <?php
    include "cfg/dbconnect.php";
    $image_path = "uploads/";
    ?>
    <div class="container">
        <h1>View Users</h1>
        <div class="table-responsive">
            <table class="table table-bordered table-stripe">
                <thead class="table-dark">
                    <tr>
                        <th>Serial No.</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Photo</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "select * from user_profile order by name";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result->num_rows > 0) {
                        $counter = 0;
                        foreach ($result as $row) {
                            $counter++;
                    ?>
                            <tr>
                                <td><?= $counter ?></td>
                                <td><?= $row['name'] ?></td>
                                <td><?= $row['email'] ?></td>
                                <td>
                                    <a href="javascript:void(0)" class="view" data-bs-toggle="modal" data-bs-target="#showImg" data-id=<?= $row['id'] ?>>
                                        <img class="photo" alt="Profile Photo" src="<?= $image_path . $row['image'] ?>" title="View Photo">
                                    </a>
                                </td>

                            </tr>
                        <?php
                        }
                    } else { ?>
                        <tr>
                            <td colspan="4"> No Users Found</td>
                        </tr>
                    <?php   }
                    ?>

                </tbody>
            </table>
        </div>

    </div>
    <!-- Modal to display photo -->
    <div id="showImg" class="modal fade" role="dialog">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- Display Dynamic data here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-info" data-bs-dismiss="modal">Close</button>
                </div>

            </div>
        </div>
    </div>
</body>
</html>

You can see we used our custom stylesheet (style.css) and JavaScript file (modal.js). this JS file will have our Ajax code in it. In line 49, we are calling a modal, using data-bs-target="#showImg". Use the data-id attribute to send the ID of the user to jQuery Ajax.

In line 70, we used the Bootstrap 5 modal with id "showImg". We will keep the modal body empty. When the user clicks on the photo, the Ajax script will run to get the details from the database and we will display the Ajax response in the modal body.

Ajax for displaying photo in the modal(modal.js)

The code is given in modal.js. It takes the parameter and sends an Ajax request to get the details from the database. Details are received as a response and displayed in the modal. Let's see the code below:

modal.js


// To display details in modal
$(document).on("click", ".view", function () {
     var userId = $(this).data('id');
     $.ajax({
       url:'get_user_details.php',
       type: 'post',
       data: {userId:userId},
       dataType:'text',
       success: function(response) {
              $(".modal-body").html(response);
            }
    });
});

  1. url: get_user_details.php - Request to run this php program to get the details of the users from the database.
  2. type: post - Post method is used
  3. data: {UserId:UserId} - User id sent to the request
  4. dataType: text - Response of Ajax call is text only
  5. success: Response is written in the modal body in Line 10.

Now we will see the code in get_user_details.php. It takes the user_id, selects data from the user_profile table and displays the photo and the name of the user.

Check below code from get_user_details.php


<?php 
include "cfg/dbconnect.php";
$path = "uploads/";
$user_id = $_POST['userId'];
$sql = "select * from user_profile where id = ?";
$stmt= $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
	$row = $result->fetch_assoc();
	echo '<img src="'.$path.$row['image'].'">';
	echo "<p>".$row['name']."</p>";
}

Add CSS (style.css)

Let us add the below styles. We have already added style.css in index.php

style.css


*{
  box-sizing: border-box;
}
h1{
  text-align: center;
}
.photo{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.table{
  width:60%;
  margin:auto;
  text-align: center;
}

.modal-body img{
  width:100%;
  height:auto;
}
.modal-body p{
  text-align: center;
  font-size: 25px;
  }

show image in popup on clickTest the Application

Check that Apache and MySQL services are running in your XAMPP control panel. Run localhost/modal_photo in the browser. You will see the home page is displayed with the list of users.

Click on the photo of a user, you should see the modal opened with the photo along with the name of the user as given below:

Dynamic Bootstrap Modal using PHP and Ajax

display image in modal jqueryNote

In this application, it was assumed that photos are already uploaded; we are just viewing them here. For enhancement purposes, you can add the upload photo and then let the user view it after the upload.

download php code to display Modal photo in PHP and AjaxDownload Source Code

You can download the source code by clicking on the Download button below.

onclick image popup jqueryConclusion

In this PHP tutorial, we have learned how to dynamically display image in Bootstrap modal using Ajax with PHP. We have displayed the image in the modal; you can display any other data from the database as well. I hope it will be useful to you. You can write your comments or questions in the comments section.

Post a Comment

Save my Name and Email id for future comments