Display Dynamic Data in Bootstrap Modal in PHP and MySQL with Ajax
In this step-by-step guide, you'll learn how to display dynamic data in a Bootstrap modal using PHP, MySQL, and Ajax. You can pass a parameter to the modal and use it to fetch data from a MySQL database with the help of Ajax. Then display the data in a popup modal. It will be useful when you want to show product details or user details without refreshing the page. You'll learn how to integrate Bootstrap modals with PHP and MySQL to create user-friendly interfaces for dynamic websites.
Here, when the user clicks on "View Details", course_id is sent to the modal using the "data-id" attribute. We can then get the details of the course (description, price, etc.) from the database and display them in a popup modal.
We have a related tutorial on how to display dynamic images in a Bootstrap modal, where we display an image in a popup modal instead of dynamic data. Please see the Related Tutorial section at the end of this tutorial.
Project Folders
Below is a screenshot of the folder structure and files we will be using:
We have created a folder named 'courses' under 'xampp/htdocs'.
I have created the "cfg" folder for the database connection. "css" and "js" are for the custom stylesheet and Ajax script, respectively.
index.php displays a list of courses with details such as course name, price and description of courses, etc. get_details.php is the PHP program executed as an Ajax request to get details of the courses from the database.
Create the Database Table in MySQL`
We will create a table named "training_courses" with some sample data in it. The table structure is given below:
Table: training_courses
The table has 4 columns in it.
course_id - It is the unique id of the course, primary key and auto incremented
course_name - Name of the course
price - Price of the course
course_details - Detail description of the course
You can use the script below to create the table with sample data. You can also download the code by clicking on the Download button given later in this tutorial.
training_courses.sql
CREATE TABLE `training_courses` (
`course_id` int(11) NOT NULL,
`course_name` varchar(255) NOT NULL,
`price` decimal(8,2) NOT NULL,
`course_details` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `training_courses` (`course_id`, `course_name`, `price`, `course_details`) VALUES
(1, 'Beginners\' course in PHP', '500.00', 'This course is aimed for persons who do not have any knowledge in PHP. It starts with the basics of PHP and then move into the writing program in PHP. Also, it gives an overview of HTML and CSS which are prerequisite to learn PHP. This is a 2 months training program and very well organized for a beginner. If you are looking for a training program in PHP, this course is the best for you.'),
(2, 'HTML and CSS', '400.00', 'This course provides the learning knowledge in HTML and CSS. It starts with basics and aimed for beginners and provides basic HTML and CSS along with Bootstrap and some basics of JavaScript. This is a one-month program where students will have ample opportunity to do practical. Trainers are very experienced and very organized to make sure every student gets his/her question answered. Go for this course if you want to start your career in web development.'),
(3, 'Java Language', '500.00', 'This course provides basic of Object-Oriented Programming and starts with basic Java Program. If you have some knowledge in any programming language it will be easier for you to start this course. This is 2 months training program. You will learn OOP programming style, class, object, Java Library, string functions. Also, there will be project work each student has to complete to have more practical knowledge in Java.'),
(4, 'Python and Django', '600.00', 'This course is for students who want to learn Python. This course provides an in-depth knowledge in Python program including Django framework. It is a one-month program. Prerequisite required for this course is: basic knowledge in HTML, CSS, JavaScript and MySQL. There are lot of hands-on works and you will complete the course with a Project.');
ALTER TABLE `training_courses`
ADD PRIMARY KEY (`course_id`);
ALTER TABLE `training_courses`
MODIFY `course_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
Write the PHP code to Connect to MySQL Database (dbconnect.php)
We will use the below PHP code to connect to a MySQL database. We will use the "test" database.
We created a mysqli object, $conn, with the parameters as server, userid, password and database name. We will use this mysqli object to execute SQL statements.
You can also read the tutorial How to connect to MySQL database in PHP using MySQLi and PDO.
Display the courses in an HTML table(index.php)
Using index.php, we will display courses in an html table. This is supposed to be very simple. All we need to do is select all the data from the "training_courses" table, then fetch them in a loop and display them in an HTML table.
Below is a list of courses displayed by index.php
Get the data from the database
<?php
include "cfg/dbconnect.php";
$sql = "select * from training_courses order by course_name";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
?>
Display courses
Let's see the code for displaying courses in an html table
If you see the last column of the table, "Course Details", a modal is called. course_id is sent as a parameter to the modal using a data-id attribute. This ID will be used by Ajax to fetch data for this course. Now, let's define the modal.
Add a Bootstrap 5 Modal
We have used the Bootstrap 5 modal here, which has a header, body and footer. See the code below:
Note that the modal-body is empty, using Ajax, we will display the details in the modal body. When a user clicks on "View Details", Ajax script will request data from the server and display the content in the modal-body.
// To display details in a modal
$(document).on("click", ".view", function () {
var courseId = $(this).data('id');
$.ajax({
url:'get_details.php',
type: 'post',
data: {courseId:courseId},
dataType:'text',
success: function(response) {
$(".modal-body").html(response);
}
});
});
In line 3, we get the course ID, which was sent using the data-id parameter earlier.
url: get_details.php - request call to the php program to get the details of the course from the database.
type: post - Post method is used
data: {courseId:courseId} - course id is sent with the request
dataType: text - response from Ajax is in text format
success: When Ajax successfully gets a response, we write the response in a modal. In Line 10 above, details are displayed in the modal body.
Let us look at the php code in get_details.php to get course details. This program takes the course_id, selects data from the "training_course" table for that course_id and displays the course name, course details and price. The output is sent back to Ajax as a response and is finally displayed in the modal.
These are simple styles. You can always add or change to make the screen look better. Keep this style.css file in your css folder.
Test the Application
Check the XAMPP control panel; Apache and MySQL services should be running. Run localhost/courses in the browser. You will see the course details are displayed. Click on "View Details" of any course, and you should see the modal open with the course details and price displayed in it.
Note
This was just an example to show how you can display details in a modal by fetching data from the database using Ajax. Field names and details used here are to simplify the example.
We have used Bootstrap Modal, which is very easy and simple to use.
Download Source Code
Download the source code by clicking on the Download button below.
Conclusion
In this tutorial, we have learned how to display dynamic data in a Bootstrap modal using PHP and MySQL with Ajax to create interactive web applications. By integrating Bootstrap modals with PHP and MySQL database, you can show or manage data dynamically without reloading the page, improving both user experience and performance. You can use this for projects like product previews or user detail popups.
Please write your comments/questions in the Comments section below. Your questions, doubts and suggestions are always welcome.
1 Thought on "Display Dynamic Data in Bootstrap Modal in PHP and MySQL with Ajax"
Post a Comment