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.

See below the code snippet:


<a href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#showDetails" class="view" data-id="<?php echo $row['course_id'];?>" >View Details</a>

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.

How to Load Dynamic Content in Bootstrap ModalProject Folders

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

Show dynamic data on modal popup using php folder structure

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

How to open modal using Ajax table structure

The table has 4 columns in it.

  1. course_id - It is the unique id of the course, primary key and auto incremented
  2. course_name - Name of the course
  3. price - Price of the course
  4. 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.

dbconnect.php


<?php
  $server="localhost";
  $userid="root";
  $pwd="";
  $dbname="test";
  $conn = new mysqli($server, $userid, $pwd, $dbname);
//Check connection
if ($conn->connect_error) {
  die("DB Connection Error: " . $conn->connect_error);
}

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

Onclick popup modal jquery

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


   <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <thead class="table-dark">
          <tr>
            <th>Course Id</th>
            <th>Course Name</th>
            <th>Price</th>
            <th>Course Details</th>
          </tr>
        </thead>
        <tbody>
          <?php
          if ($result->num_rows > 0) {
            foreach ($result as $row) { ?>
              <tr>
                <td><?= $row['course_id']; ?></td>
                <td><?= $row['course_name']; ?></td>
                <td><span class="fa fa-usd"></span> <?= $row['price']; ?></td>
                <td><a href="javascript:void(0)" class="view" data-bs-toggle="modal" data-bs-target="#showDetails" data-id="<?= $row['course_id']; ?>">View Details</a></td>
              </tr>
            <?php }
          } else { ?>
            <tr>
              <td colspan="4">No Courses found</td>
            </tr>
          <?php } ?>
        </tbody>
      </table>
    </div>

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:


<div id="showDetails" class="modal fade" role="dialog">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Display Dynamic data here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-info" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

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.

Below is the complete index.php

index.php


<!DOCTYPE html>
<html lang="en">

    <head>
        <title>Training Courses</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="css/style.css">

        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
        <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
        <script src="js/modal_scripts.js"></script>
    </head>

    <body>
        <?php
  include "cfg/dbconnect.php";
  $sql = "select * from training_courses order by course_name";
  $stmt = $conn->prepare($sql);
  $stmt->execute();
  $result = $stmt->get_result();
  ?>

        <div class="container">
            <h1>Training Courses</h1>
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead class="table-dark">
                        <tr>
                            <th>Course Id</th>
                            <th>Course Name</th>
                            <th>Price</th>
                            <th>Course Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
          if ($result->num_rows > 0) {
            foreach ($result as $row) { ?>
                        <tr>
                            <td>
                                <?= $row['course_id']; ?>
                            </td>
                            <td>
                                <?= $row['course_name']; ?>
                            </td>
                            <td><span class="fa fa-usd"></span>
                                <?= $row['price']; ?>
                            </td>
                            <td><a href="javascript:void(0)" class="view" data-bs-toggle="modal"
                                    data-bs-target="#showDetails" data-id="<?= $row['course_id']; ?>">View Details</a>
                            </td>
                        </tr>
                        <?php }
          } else { ?>
                        <tr>
                            <td colspan="4">No Courses found</td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- Modal to display the details of course -->
        <div id="showDetails" class="modal fade" role="dialog">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Display Dynamic data here -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-info" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </body>

</html>

Write Ajax code (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);
            }
    });
});

In line 3, we get the course ID, which was sent using the data-id parameter earlier.

  1. url: get_details.php - request call to the php program to get the details of the course from the database.
  2. type: post - Post method is used
  3. data: {courseId:courseId} - course id is sent with the request
  4. dataType: text - response from Ajax is in text format
  5. 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.

Check the code below for get_details.php

get_details.php


<?php include "cfg/dbconnect.php";
$course_id = $_POST['courseId'];
$sql = "select * from training_courses where course_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $course_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
	$row = $result->fetch_assoc();
	echo "<h4>Course Name: ".$row['course_name']."</h4>";
	echo "<p>".$row['course_details']."</p>";
	echo "<p><b>Price:</b> <span class='fa fa-usd'></span> ".$row['price']."</p>";
}

Add CSS (style.css)

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

style.css


*{
    box-sizing: border-box;
}
.table{
    width: 60%;
    margin:auto;
    text-align: center;
}
h1,h4{
    text-align: center;
}

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.

display dynamic data in modal in phpTest 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.

How to show dynamic data in popup with jQuery

bootstrap modalNote

  1. 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.
  2. We have used Bootstrap Modal, which is very easy and simple to use.

download php code to display details in Modal dynamically in PHP and AjaxDownload Source Code

Download the source code by clicking on the Download button below.

Display data in bootstrap Modal dynamically in PHP and AjaxConclusion

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

Save my Name and Email id for future comments