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:
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:
We created a folder named 'modal_photo' under 'xampp/htdocs'.
Folder 'cfg' - In this folder, we have kept dbconnect.php which is used to connect to the MySQL database.
Folder 'css' - Our custom stylesheet is in this folder
Folder 'js' - In this folder, we have our custom JavaScript file which has Ajax script in it to display the photo in a modal.
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.
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.
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:
id - It is the unique id of a user, primary key and auto incremented
name - Name of the user
email - Email of the user
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.
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
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:
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);
}
});
});
url: get_user_details.php - Request to run this php program to get the details of the users from the database.
type: post - Post method is used
data: {UserId:UserId} - User id sent to the request
dataType: text - Response of Ajax call is text only
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
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:
Note
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 Source Code
You can download the source code by clicking on the Download button below.
Conclusion
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