Dynamically load content in Bootstrap Modal with AJAX

Modals are one of the many pre-built components offered by the widely used front-end web development framework Bootstrap. Developers can display content on top of an existing page by using dialogue boxes or pop-up windows known as modals.

However, there are times when need to dynamically load content into the Modal, which is possible with AJAX.

AJAX allows data to be loaded and displayed on a page without having to reload the entire page, making the web application faster and more user-friendly.

In this tutorial, I will show you how to dynamically load MySQL database content into a Bootstrap Modal using AJAX and PHP.

I am using Bootstrap 5 in the example, if you are using any other version then also you can follow.

Dynamically load content in Bootstrap Modal with AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML – Create Modal & Table layout
  4. AJAX – Return Bootstrap Modal Data
  5. jQuery – Send AJAX request to Dynamically Load Content
  6. Demo
  7. Conclusion

1. Table structure

Create employee table.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `emp_name` varchar(100) NOT NULL,
  `salary` varchar(50) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `city` varchar(80) NOT NULL,
  `email` varchar(100) NOT NULL
);

2. Configuration

Create a config.php for the database connection.

Completed Code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

3. HTML – Create Modal & Table layout

Create a single Bootstrap Modal to display user information. Modal body is empty, data gets populated using jQuery AJAX.

List employee table records in tabular format. Here, also added an Info button that has userinfo class and stored employee id in data-id attribute. On this button click load content in a modal using AJAX.

Completed Code

<?php 
include "config.php";
?>
<!doctype html>
<html>
<head>
     <title>Dynamically load content in Bootstrap Modal with AJAX</title>
     <!-- CSS -->
     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
     
     <!-- Script -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
     <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
 </head>
 <body >
     <div class="container" >
          <!-- Modal -->
          <div class="modal fade" id="empModal" >
                <div class="modal-dialog">
 
                      <!-- Modal content-->
                      <div class="modal-content">
                           <div class="modal-header">
                                <h4 class="modal-title">User Info</h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                           </div>
                           <div class="modal-body">
 
                           </div>
                           <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                           </div>
                      </div>
                </div>
          </div>
          <br/>

          <!-- Employees List -->
          <table class='table' border='1' style='border-collapse: collapse;'>
               <tr>
                   <th>Name</th>
                   <th>Email</th>
                   <th>&nbsp;</th>
               </tr>
               <?php 
               $query = "select * from employee";
               $result = mysqli_query($con,$query);
               while($row = mysqli_fetch_array($result)){
                    $id = $row['id'];
                    $name = $row['emp_name'];
                    $email = $row['email'];

                    echo "<tr>";
                    echo "<td>".$name."</td>";
                    echo "<td>".$email."</td>";
                    echo "<td><button data-id='".$id."' class='userinfo'>Info</button></td>";
                    echo "</tr>";
               }
               ?>
          </table>
 
     </div>
</body>
</html>

4. AJAX – Return Bootstrap Modal Data

Create ajaxfile.php file.

Read POST userid value and assign it to $userid variable. Select a record from employee table where id=$userid. Read the fetched data and create a table layout and assign it to $response variable.

Return the $response.

Completed Code

<?php
include "config.php";

$userid = 0;
if(isset($_POST['userid'])){
    $userid = mysqli_real_escape_string($con,$_POST['userid']);
}
$sql = "select * from employee where id=".$userid;
$result = mysqli_query($con,$sql);

$response = "<table border='0' width='100%'>";
while( $row = mysqli_fetch_array($result) ){
    $id = $row['id'];
    $emp_name = $row['emp_name'];
    $salary = $row['salary'];
    $gender = $row['gender'];
    $city = $row['city'];
    $email = $row['email'];
 
    $response .= "<tr>";
    $response .= "<td>Name : </td><td>".$emp_name."</td>";
    $response .= "</tr>";

    $response .= "<tr>";
    $response .= "<td>Salary : </td><td>".$salary."</td>";
    $response .= "</tr>";

    $response .= "<tr>";
    $response .= "<td>Gender : </td><td>".$gender."</td>";
    $response .= "</tr>";

    $response .= "<tr>";
    $response .= "<td>City : </td><td>".$city."</td>";
    $response .= "</tr>";

    $response .= "<tr>"; 
    $response .= "<td>Email : </td><td>".$email."</td>"; 
    $response .= "</tr>";

}
$response .= "</table>";

echo $response;
exit;

5. jQuery – Send AJAX request to Dynamically Load Content

Define click event on userinfo class. Read data-id attribute value and assign it to userid variable.

Send AJAX POST request to ajaxfile.php file. Here, pass {userid: userid} as data. On successful callback append response in .modal-body and display the modal calling show method.

Completed Code

$(document).ready(function(){

    $('.userinfo').click(function(){
   
         var userid = $(this).data('id');

         // AJAX request
         $.ajax({
               url: 'ajaxfile.php',
               type: 'post',
               data: {userid: userid},
               success: function(response){ 
                    // Add response in Modal body
                    $('.modal-body').html(response);

                    // Display Modal
                    $('#empModal').modal('show'); 
               }
         });
    });
});

6. Demo

View Demo


7. Conclusion

Use AJAX when you want to use a single Bootstrap Modal to display information according to various requests otherwise, you can simply create multiple Modal with information for each task.

If you found this tutorial helpful then don't forget to share.

39 thoughts on “Dynamically load content in Bootstrap Modal with AJAX”

    • The value is not POST from AJAX request. I checked the page button element not has userid attached in the id attribute (‘butinfo_’). The page will start working correctly when you fix this.

      Reply
  1. working perfectly. Thank you.
    I have a problem. Can you help me?
    I have another modals on page.
    $(‘.modal-body’).html(response);
    Adding response in ALL Modal bodies.
    How can I change this.

    Reply
  2. Hi Sir..i have used the above code and when i pass entire table from controller and display it into modal,it displays table tags along with data.can you help me with this issue

    Reply
  3. السلام عليكم
    شكرا جزيلا لكم.
    Thank you very much, can you help me how to pass multiple parameters with json.

    Reply
  4. I am getting errors, the POST method doesn’t actually post the work!
    mainphpfile

    Herbal

    About

    Health
    Health
    Health
    Health
    Health

    Tips

    Health
    Health
    Health
    Health
    Health

    Important!

    Health
    Health
    Health
    Health
    Health

    num_rows; // Find total rows returned by database
    if($rows > 0) {
    $cols = 3; // Define number of columns
    $counter = 1; // Counter used to identify if we need to start or end a row
    $nbsp = $cols – ($rows % $cols); // Calculate the number of blank columns

    //$container_class = ‘container-fluid’; // Parent container class name
    $row_class = ‘row’; // Row class name
    $col_class = ‘col-md-4’; // Column class name

    //echo ”; // Container open
    while ($item = $result->fetch_array()) {
    $item_id = $item[‘item_id’];
    if(($counter % $cols) == 1) { // Check if it’s new row
    echo ”; // Start a new row
    }
    //$img = “classes/Medicines/”.$item[‘image_name’];
    //echo ”.$item[‘name’].”;
    echo ‘ ‘?>

    <img src="classes/Medicines/” alt=”image” width=”40%”>

    Add to Cart   
    <button style="width:150px;" data-id="” class=’item_info’>Click to view details

    <?php
    // Column with content
    if(($counter % $cols) == 0) { // If it's last column in each row then counter remainder will be zero
    echo '’; // Close the row
    }
    $counter++; // Increase the counter
    }
    $result->free();
    if($nbsp > 0) { // Adjustment to add unused column in last row if they exist
    for ($i = 0; $i < $nbsp; $i++) {
    echo ' ‘;
    }
    echo ”; // Close the row
    }
    //echo ”; // Close the container
    }
    ?>

    User Info
    ×

    Close

    $(document).ready(function(){

    $(‘.item_info’).click(function(){

    var item_id = $(this).data(‘item_id’);

    // AJAX request
    $.ajax({
    url: ‘ajaxmodal.php’,
    type: ‘post’,
    data: {item_id: item_id},
    success: function(response){
    // Add response in Modal body
    $(‘.modal-body’).html(response);

    // Display Modal
    $(‘#empModal’).modal(‘show’);
    }
    });
    });
    });

    ajax-file
    <?php
    include('database/connect.php');

    $item_id = $_POST['item_id'];

    $sql = "SELECT * FROM item_images INNER JOIN items ON item_images.item_id = items.item_id WHERE item_id = ".$item_id;
    $results = mysqli_query($con,$sql);

    $response = "”;
    while($products = mysqli_fetch_array($results)){
    $image_name = $products[‘image_name’];
    $item_name = $products[‘item_name’];
    $item_price = $products[‘item_price’];
    $item_description = $products[‘item_description’];
    $publisher = $products[‘publisher’];
    $prescription = $products[‘prescription’];

    $response .= “”;
    $response .= “”.$item_price.””;
    $response .= “”.$item_description.””;
    $response .= “”.$publisher.””;
    $response .= “”.$prescription.””;
    $response .= “Add to Cart”;

    }
    $response .= “”;

    echo $response;
    exit;
    ?>

    Reply
  5. Thanks a lot for this helpful article. In my case, in order to correctly display characters in my native language, I had to add the line to the ajax file.php: mysqli_set_charset ($ con, “utf8”);

    I wanted to add the possibility of showing further data without closing the modal. So I want to add the previous and next arrows as objects in the div which will have data-id. Can you suggest how to display new data in the same modal after pressing such an element?

    Reply
  6. I saw this early on and thought… NOOOoooooo…. “.load() will be easier!”

    DUMBASS. I was a dumbass. DON’T use .load().

    For some reason the bootstrap JS will not load properly and will leave you with the data, but no visibility (and then you can try and toggle it, but it just doesn’t work right).
    SKIP THAT NIGHTMARE!!!
    THIS. RIGHT HERE. This is THE answer!

    THANK YOU!

    Reply
  7. Thank you clear and well done.
    Googling around I see there is .load for modals
    Why don’t you update your post showing us that alternative method ?

    cheers

    Reply
  8. How can I implement same with codeigniter? Even my populated model also contains table. How can I fill thatt? Here I added some of my code
    Controller:
    function getPrevstage($id){
    $data[‘prev’] = $this->myModel->get_prevStage($id);
    echo json_encode($data);
    }
    View:

    1
    2</th

    —How can I fill this tbody section

    jQuery:
    $(‘.prevApprov’).click(function(){
    var id = $(this).data(‘refid’);
    $.ajax({
    url : ‘mu URL’,
    type : POST,
    data : {refid : refid},
    success : function(data){
    $(‘.modal-body’).html(data);
    }
    });
    })

    Reply
    • Hi Sowmya,
      You are returning a JSON response from the controller. In the AJAX request add dataType: ‘json’. You need to loop on the AJAX response to append data to the modal body.

      Reply
  9. somehow my code is not working
    index.php =
    https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js
    /path/to/bootstrap/js/bootstrap.min.js

    $(document).ready(function() {

    $(‘.btn1’).click(function() {

    var userid = $(this).data(‘id’);

    // AJAX request
    $.ajax({
    url: ‘data.php’,
    type: ‘post’,
    data: {
    ‘userid’: userid
    },
    success: function(response) {
    // Add response in Modal body
    $(‘.modal-content’).html(response);

    // Display Modal
    $(‘#myModal’).modal(‘show’);
    }
    });
    });
    });
    $(document).ready(function() {});

    0) {
    echo ”

    #
    Naam
    Adres
    E-mail
    Actie
    “;
    while ($row = mysqli_fetch_assoc($result)) {
    $id = $row[‘id’];
    echo “”;
    echo “” . $id . “”;
    echo “” . $row[‘naam’] . “”;
    echo “” . $row[‘adres’] . “”;
    echo “” . $row[’email’] . “”;
    echo ”

    <img id='myBtn' class='pen' src='pen.png'
    “;
    }
    }
    echo “”;
    ?>
    data.php =
    error;
    }
    $conn->close();
    }
    $userid = $_POST[“userid”];
    $sql = “SELECT * FROM popup WHERE id = ” . $userid;
    $result = mysqli_query($conn, $sql);
    echo ”

    #
    Naam
    Adres
    E-mail
    Actie
    “;
    while ($row = mysqli_fetch_array($result)) {
    echo “”;
    echo “” . $row[‘id’] . “”;
    echo “” . $row[‘naam’] . “”;
    echo “” . $row[‘adres’] . “”;
    echo “” . $row[’email’] . “”;
    echo “Wijzig”;
    echo “”;
    }
    echo “”;

    mysqli_close($conn);
    ?>

    Reply
  10. FINALLY!! after searching several month for a working example for loading dynamic data with jquery and php/mysql I finnally found this. AND IT WORKS!!!

    THANK YOU…THANK YOU THANK YOU!!

    Reply
  11. Somehow my modal is not displaying without data-toggle and data-target. When i include both, the modal shows but there is no data in the modal-body

    Here’s my code
    reservationsList.php


    https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js

    https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js

    Customer Pre-Order / Message
    ×

    Close

    Name
    Contact
    Date
    Time
    Seats
    Message / Orders
    Accept/Reject/Cancel

    <?php
    $query = "SELECT * FROM reservation ORDER BY reservation_id DESC";
    $result = mysqli_query($con, $query);
    while($row = mysqli_fetch_assoc($result)) {
    $id = $row['reservation_id'];
    $name = $row['name'];
    $contact = $row['contact'];
    $date = $row['date'];
    $time = $row['time'];
    $seats = $row['seats'];
    $orders = $row['orders'];
    $message = $row['message'];
    $status = $row['status'];

    echo "”;
    echo “”.$name.””;
    echo ““.$contact.””;
    echo “”.$date.””;
    echo “”.$time.””;
    echo “”.$seats.””;
    echo “Info”;
    echo ”
    Actions
    “;
    echo “”;
    }
    ?>

    $(document).ready(function() {
    $(‘.orderInfo’).click(function(){
    var userid = $(this).data(‘reservation_id’);

    $.ajax({
    url: ‘ajaxfile.php’,
    type: ‘post’,
    data: {userid: userid},
    success: function(response){
    $(‘.modal-body’).html(response);

    $(‘#modal-info’).modal(‘show’);
    }
    });
    });
    });

    ajaxfile.php

    <?php

    include "process/db_connect.php";

    $userid = $_POST['userid'];

    $query = "SELECT * FROM reservation WHERE reservation_id=".$userid;
    $result = mysqli_query($con, $query);

    $response = "”;

    while($row = mysqli_fetch_assoc($result)){
    $id = $row[‘reservation_id’];
    $orders = $row[‘orders’];
    $message = $row[‘message’];

    $response .= “”;
    $response .= “Orders: “.$orders.””;
    $response .= “”;

    $response .= “”;
    $response .= “Messages: “.$message.””;
    $response .= “”;
    }

    $response .= “”;

    echo $response;
    exit;

    ?>

    Reply
  12. I would like to display drop down data from DB. Then user can modify the transation. When i write the code as below, i received Fatal Error 86. Can you help me out with that please.
    $response .=””;
    $response .=”Transport Unternehmer:
    while($rowtu = mysqli_fetch_array($restu)) {
    echo(‘”.$rowtu[‘unternehmer’].”‘);
    }
    “;
    $response .=””;

    Reply
  13. in my modal modal body is not showing… modal header and footer working properply but modal body input fiels and labels is not visible

    $(document).ready(function(){

    $(‘.ddata’).click(function(){

    var userid = $(this).data(‘id’);

    // AJAX request
    $.ajax({
    url: ‘http://192.168.10.11:8012/security/web-api/Setup/qualification/qualification_insert_api.php’,
    type: ‘post’,
    data: {userid: userid},
    success: function(response){
    // Add response in Modal body
    $(‘.modal-body’).html(response);

    // Display Modal
    $(‘#exampleModal’).modal(‘show’);
    }
    });
    });
    });

    Reply

Leave a Comment