Show Dynamic Data in a Bootstrap Modal in PHP and Ajax
You can display dynamic data in a Bootstrap modal by passing a parameter to the modal and fetching data from MySQL database. Using PHP, MySQL and Ajax you can show dynamic data in a Bootstrap modal.
In this topic, we will develop an application to show how to display data in a modal from the database. There could be cases where you may NOT want to show descriptive information on the page itself. Instead, you want the user to click on a link and view the descriptive data in a modal. See below the code snippet:
Here, if the user clicks on "View Details", using the "data-id" attribute, course_id is sent to the modal. Using Ajax, we can then get details for the course (like description, price, etc.) and display in a modal.
Folders and Files
Below is a screenshot of the folder structure and files we will be using:
We have created a folder named 'courses' under 'xampp/htdocs'.
Folder 'cfg' - This is for dbconnect.php to connect to the MySQL database.
Folder 'css' - Custom stylesheet is in this folder
Folder 'js' - We have our custom JavaScript file which has an Ajax script in it to display the details of a course in a modal.
index.php displays a list of courses with details such as course name, price and description of courses, etc. But the user has to click on "View Details" to see the description of a course.
get_details.php - It is the PHP program executed as an Ajax request to get details of the courses from the database.
Below is the screenshot of output displayed by index.php
In the above screen, you can see a list of courses displayed, by clicking on the "View Details" link, the user can see the detailed description of a course.
Create a MySQL table for the courses
The table name is 'training_courses'. This table has the course name, price, etc. 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
Create table script with data for this table is given below. You can also download the code by clicking on the Download button given later in this topic.
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;
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.
Using index.php, we will display a list of courses in an html table. This is supposed to be very simple. All we need to do is select the rows from the training_courses 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 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. A parameter which is course_id is sent to the modal using a data-id attribute. This id will be accessed by a JavaScript function to run Ajax. Now let's define the modal.
The Modal
We have used the Bootstrap modal here which has a header, body and footer. See the below code:
Note that the modal-body is empty now, using Ajax we will display the detail in the modal body. When a user clicks on "View Details", Ajax script will request data from the server and display the content here.
Write Ajax script for modal display (modal_scripts.js)
modal_scripts.js
// 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);
},
error: function (request, status, error) {
$(".modal-body").html(request.responseText);
}
});
});
url: get_details.php - request call to the php program which gets details of the course from the database.
type: post - Post method is used
data: {id:id} - 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 training_course table for that course_id and displays course name, course details and price. The output will be given back to Ajax as response and will be displayed in the modal finally.
Check below code form get_details.php
get_details.php
<?php include "cfg/dbconnect.php";
$course_id = $_POST['courseId'];
$sql = "select * from training_courses where course_id = '$course_id'";
$rs = mysqli_query($conn,$sql);
if (mysqli_num_rows($rs) > 0) {
$row = mysqli_fetch_array($rs);
echo "
Course Name: ".$row['course_name']."
";
echo "
".$row['course_details']."
";
echo "
Price:".$row['price']."
";
}
Add CSS (style.css)
Let us add the below styles. I have already added style.css in index.php
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, you should see the modal opened with the course details and price displayed on 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 example, we have coded how to display dynamic data in a modal using Ajax. This was just an example to show details in the modal after fetching data from the database. You can use it anywhere in your project for a similar requirement.
I have tried to explain the topic in detail as far as possible for your easy understanding. I hope it will be useful to you.
Post a Comment