Dynamically Load Data in a Bootstrap Modal in 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 to display an image in a Bootstrap modal along with other details from the 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:
When a user clicks on a photo, id of the user 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 have 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 for users
Let us create a table named 'user_profile' in MySQL database. This table will have user details, like name, email, photo, etc. The table structure is given below:
Table has four columns.
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 below script to connect to the database. We will keep this file under cfg folder.
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
Display users
Let's see the code for displaying user details in an HTML table:
Users are selected from the 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 the data-id attribute to send the ID of the user to the modal. We are using the Bootstrap modal and it is given below:
We will keep the modal body empty, later we will display the detail here. When the user clicks on the photo, an 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; the link is given later in this topic.
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);
},
error: function (request, status, error) {
$(".modal-body").html(request.responseText);
}
});
});
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";
<?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 the below styles. We have already added style.css in index.php
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.
Test 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:
Note
In this application it was assumed that photos are already uploaded, we are just viewing them here. For enhancement purpose, 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 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 requirements.
Post a Comment