Pass data to bootstrap modal and show dynamic data 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 you can 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:


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

Here, if the user clicks on "View Details", using "data-id" attribute, course_id is being sent to the modal. Using Ajax, we can then get details for the course (like description, price etc.) and display in a modal.

How to Load Dynamic Content in Bootstrap ModalFolders and Files

Below is a screenshot of the folder structure and files I am using:

How to pass dynamic data in bootstrap modal

We have created a folder named 'courses' under 'xampp/htdocs'.

  1. Folder 'cfg' - This is for dbconnect.php to connect to the MySQL database.
  2. Folder 'css' - Custom stylesheet is in this folder
  3. Folder 'js' - We have our custom JavaScript file which has Ajax script in it to display the details of a course in a modal.
  4. index.php displays a list of courses with details such as course name, price and description of courses etc. But user has to click on "View Details" to see the description of courses.
  5. get_details.php - It is the PHP program executed as Ajax request to get details of the courses from database.

Below is the screenshot of output displayed by index.php

How do you make a modal dynamic

In the above screen, you can see a list of courses are displayed, by clicking on the "View Details" link, user can see the detail description of a course.

Create a MySQL table for the courses

The table name is 'training_courses'. This table has course name, price etc. Table structure is given below:

Table: training_courses

how to open modal using ajax

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
Create table script with data for this table is given below. You can also download the code by clicking on 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 MySQL database. We will use "test" database.

dbconnect.php


<?php
  $server="localhost";
  $userid="root";
  $pwd="";
  $dbname="test";
  $conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn) 
  	die("Connection Error: " . mysqli_connect_error());

We are using mysqli_connect() function with four parameters.

  1. server - our server is localhost
  2. userid - root user
  3. password - no password for the user root
  4. database name - test in our case.

If connection is successful, it will return true. We will include this dbconnect.php in other php programs. You can also read the topic How to connect to MySQL database in PHP using MySQLi and PDO.

Display a list of courses (index.php)

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 training_courses table using a select statement, then fetch them in a loop and display in an HTML table.

Below is the list of courses displayed by index.php

onclick popup modal jquery

Display courses

Let's see the code for displaying courses in a table


<div class="table-responsive">
  <table class="table table-bordered table-striped">
   <tr>
     <thead>
     <th>Course Id</th><th>Course Name</th><th>Price</th><th>Course Details</th>
     </thead>
   </tr>
   <?php 
   $sql = "select * from training_courses order by course_name";
   $rs = mysqli_query($conn,$sql); 
   if (mysqli_num_rows($rs) >0) {
     foreach ($rs as $row) { ?>
     <tr>
       <td><?php echo $row['course_id'];?></td>
       <td><?php echo $row['course_name'];?></td>
       <td><span class="fa fa-usd"> <?php echo $row['price'];?></span></td>
       <td><a href="javascript:void(0)" data-toggle="modal" data-target="#showDetails" class="view" data-id="<?php echo $row['course_id'];?>" >View Details</a></td>
     </tr>
   <?php } 
   }
   else { ?>
     <tr><td colspan="7">No Courses found</td></tr>
     <?php } ?>
  </table>
 </div>

If you see the last column of the table which is "Course Details", a modal is called. A parameter which is course_id is sent to the modal using data-id attribute. This id will be accessed by JavaScript function to run Ajax. Now let's define the modal.

The Modal

We have used Bootstrap modal here which has header, body and footer. See the code below:


<div id="showDetails" class="modal fade course" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h2>View Course Details</h2>
      </div>
      <div class="modal-body">
        
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Note that 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.

Below is the full index.php

index.php


<?php include "cfg/dbconnect.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 rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <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://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="js/modal_scripts.js"></script>
</head>
<body>
    <div class="container">
      <h3>Training Courses</h3>
      <div class="table-responsive">
       <table class="table table-bordered table-striped">
        <tr>
          <thead>
          <th>Course Id</th><th>Course Name</th><th>Price</th><th>Course Details</th>
          </thead>
        </tr>
        <?php 
        $sql = "select * from training_courses order by course_name";
        $rs = mysqli_query($conn,$sql); 
        if (mysqli_num_rows($rs) >0) {
          foreach ($rs as $row) { ?>
          <tr>
            <td><?php echo $row['course_id'];?></td>
            <td><?php echo $row['course_name'];?></td>
            <td><span class="fa fa-usd"> <?php echo $row['price'];?></span></td>
            <td><a href="javascript:void(0)" data-toggle="modal" data-target="#showDetails" class="view" data-id="<?php echo $row['course_id'];?>" >View Details</a></td>
          </tr>
        <?php } 
        }
        else { ?>
          <tr><td colspan="7">No Courses found</td></tr>
          <?php } ?>
       </table>
      </div>
    </div>
<!-- Modal to display the details of course -->
<div id="showDetails" class="modal fade course" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h2>View Course Details</h2>
        </div>
        <div class="modal-body">
          
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
</div>
</body>
</html>

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);
}
    });
});

  1. url: get_details.php - request call to the php program which gets details of the course from the database.
  2. type: post - Post method is used
  3. data: {id:id} - course id is sent with the request
  4. dataType: text - response from Ajax is in text format
  5. success: When Ajax successfully gets response, we write the response in a modal. In Line 10 above, details are displayed in the modal-body.

Now, let us look at the php code in get_details.php to get course detail. This program simply 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 below styles. I have already added style.css in index.php

style.css


h3{
  text-align: center;
  margin-top: 20px;
}
h2{
  text-align: center;
  width: 100%;
  }
table{
  width:80%;
}
table,th,td {
  margin:auto;
  border-collapse: collapse;
  border:1px solid #c4b2b2;
  }
thead {
  background-color: #265159;
  color:#fff;

}
thead,tbody {
  text-align: center;
}
.course .modal-body{
	height:350px;
	overflow-y:auto;
}
.course .modal-body p{
	line-height:26px;
	margin-top:20px;
}
.modal-dialog .modal-header {
	display:block;
}

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 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 are displayed in it.

How to show dynamic data in popup with jQuery

Hope you could understand all the steps and you could test it successfully.

bootstrap modalNote

  1. This was just an example to show how you can display details in a modal by fetching data from database using Ajax. Field names and details used here are just 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 example, we have coded how you can display dynamic data in a modal using Ajax. This was just an example to show details in modal after fetching data from database. You can use it anywhere in your project for similar requirement.

I have tried to explain the topic in detail as far as possible for your easy understanding. Hope it will be useful to you.