Dynamically load data and image in Bootstrap modal using PHP and Ajax

There could be many instances when you want to display information in a modal popup screen. Even some time we need to display a photo along with some details of the photo in a modal. Presenting the information in this format gives a better user experience.

In this topic, we will develop an application to show how you can display an image in a Bootstrap modal along with other details from database using PHP and Ajax dynamically.

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

Show dynamic data on modal popup using php

When a user clicks on a photo, id of the user is sent to a modal using "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-toggle="modal" data-target="#showImg" class="view" data-id="<?php echo $row['id']; ?>" >
<img class="photo" alt="Profile Photo" src="<?php echo $image_path.$row['image']; ?>" title="View Photo"/>
    </a>

What is the AJAX model in PHPFolders and Files

Below is a screenshot of the folder structure and files we will be using:

Bootstrap Modal with Dynamic MySQL Data using Ajax

We have 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 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. 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 Ajax request to get details of the users from the database.

Create a MySQL table for users

Let us create a table named 'user_profile' in MySQL database. This table will have user details, like name, email, photo etc. Table structure is given below:

image popup on click bootstrap

Table has four columns.

  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 below script to connect to the database. We will keep this under cfg folder.

dbconnect.php


<?php
  $server="localhost";
  $userid="root";
  $pwd="";
  $dbname="test";
  $conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn) 
  	die("Connection Error: " . mysqli_connect_error());

We are using using mysqli_connect() function with the below parameters.

  1. server - it is localhost
  2. userid - we use root user
  3. password - no password for the user root
  4. database name - test database in our case.
We will include dbconnect.php in other php programs so that we do not need to code again in the program. You can also read the read topic How to connect to MySQL database in PHP using MySQLi and PDO.

Display a list of users (index.php)

We will display a list of users in an HTML table. Select the rows from 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

bootstrap modal with image and text

Display users

Let's see the code for displaying user details in an HTML table:


<?php
include "cfg/dbconnect.php";
$image_path="uploads/";
?>
<h2>View Users</h2>
<table class="table table-stripe table-bordered">
	 	<tr>
	 		<thead>
	 		<th>Serial No.</th><th>Name</th><th>Email</th><th>Photo</th>
	 		</thead>
	 	</tr>
	 	<?php 
	 	$sql = "select * from user_profile order by name";
	 	$rs = mysqli_query($conn,$sql);
	 	$counter = 0;
		if (mysqli_num_rows($rs) >0) {
	 	foreach ($rs as $row) { 
	 		$counter++?>
	 		<tr>
	 			<td><?php echo $counter;?>
	 			<td><?php echo $row['name'];?></td>
	 			<td><?php echo $row['email'];?></td>
	 			<td>
	 				<a href="javascript:void(0)" data-toggle="modal" data-target="#showImg" class="view" data-id="<?php echo $row['id']; ?>" >
              <img class="photo" alt="Profile Photo" src="<?php echo $image_path.$row['image']; ?>" title="View Photo"/></a>
	 			</td>
	 		</tr>
	 	<?php } 
	 }
	 	else { ?>
	 		<tr><td colspan="7">No Users found</td></tr>
	 		<?php } ?>
	 </table>

Users are selected from user_profile table and are displayed row by row in an html table. In the last column of the table ("Photo") a modal is used. Use data-id attribute to send the ID of the user to the modal. We are using Bootstrap modal and it is given below:

Modal


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

We will keep modal-body empty, later we will display the detail in modal-body. When the user clicks on the photo, Ajax script will run to get the details from the database.

Below is the complete code for index.php. You can also download the code, link is given later in this topic.

index.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>User Profile</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link  rel="stylesheet" href="css/style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="js/modal.js"></script>
</head>
<body>
  <div class="container">
<?php
include "cfg/dbconnect.php";
$image_path="uploads/";
?>
<h2>View Users</h2>
<table class="table table-stripe table-bordered">
	 	<tr>
	 		<thead>
	 		<th>Serial No.</th><th>Name</th><th>Email</th><th>Photo</th>
	 		</thead>
	 	</tr>
	 	<?php 
	 	$sql = "select * from user_profile order by name";
	 	$rs = mysqli_query($conn,$sql);
	 	$counter = 0;
		if (mysqli_num_rows($rs) >0) {
	 	foreach ($rs as $row) { 
	 		$counter++?>
	 		<tr>
	 			<td><?php echo $counter;?>
	 			<td><?php echo $row['name'];?></td>
	 			<td><?php echo $row['email'];?></td>
	 			<td>
	 				<a href="javascript:void(0)" data-toggle="modal" data-target="#showImg" class="view" data-id="<?php echo $row['id']; ?>" >
              <img class="photo" alt="Profile Photo" src="<?php echo $image_path.$row['image']; ?>" title="View Photo"/></a>
	 			</td>
	 		</tr>
	 	<?php } 
	 }
	 	else { ?>
	 		<tr><td colspan="7">No Users found</td></tr>
	 		<?php } ?>
	 </table>
</div>
<!-- Modal to display photo -->
<div id="showImg" class="modal fade profile" role="dialog">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
</div>
</body>
</html>

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

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 response and then it displays the data 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);
            },
       error: function (request, status, error) {
        $(".modal-body").html(request.responseText);
}
    });
});

  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 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";
<?php 
include "cfg/dbconnect.php";
$path = "uploads/";
$user_id = $_POST['userId'];
$sql = "select * from user_profile where id = '$user_id'";
$rs = mysqli_query($conn,$sql);
if (mysqli_num_rows($rs) > 0) {
	$row = mysqli_fetch_array($rs);
	echo '<img src="'.$path.$row['image'].'">';
	echo "<p>".$row['name']."</p>";
}

Add CSS (style.css)

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

style.css


h2{
  margin-top: 20px;
  text-align: center;
}
.photo{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
table{
  width:80%;
}
table,th,td {
  margin:auto;
  border-collapse: collapse;
  border:1px solid #c4b2b2;
  }
thead {
  background-color: #265159;
  color:#fff;

}
thead,tbody {
  text-align: center;
}
#showImg{
  outline: none;
  overflow: auto;
}

.modal-header {
    padding-bottom: 10px;
    padding-top: 0;
}
.modal-body{
    width: 100%;
    height: auto;
    overflow-y:auto;
    padding:10px;

}
.modal-body img{
  width:100%;
  height:auto;
  border:none; 
}
.modal-body p{
  text-align: center;
  font-size: 25px;
  padding-top: 0;
  color: #10109e;
  }
.modal-footer{
  padding: 2px;
}

These are simple styles. You can always add or change them to make a better design. Keep this style.css file in your css folder.

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:

In Bootstrap open Enlarge image in modal - ajax and jQuery

display image in modal jqueryNote

In this application it was assumed that photos are already uploaded, we are just viewing the photos here. For enhancement purpose you can add the upload photo and then let the user view it after 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 topic we have seen how to show details in a modal dynamically by fetching data from the database using Ajax. You can use it in your project for similar requirement.