Display Dynamic Images in a Bootstrap Modal Using CodeIgniter 3

In this tutorial, you will learn how to display dynamic images in a Bootstrap modal using CodeIgniter 3. This step-by-step guide will help you easily show images in a popup modal. You will learn how to use jQuery, Bootstrap, and CodeIgniter 3, which you can use while building an image gallery or product display.

You can display dynamic image by passing the "data-id" parameter to the modal. Take a look at the below code snippet. While calling the modal, data-id attribute is used to send a value to the modal.


<a href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#showImg" class="view" data-id="<?php echo $row->image; ?>" >
  <img class="photo" alt="Profile Photo" src="<?php echo base_url().$image_path.$row->image; ?>" title="View Photo"/>
</a>

In the above code, a modal is called when the user clicks on the image, note the 'data-id' attribute with a value of the image name. This image will be displayed in a bootstrap modal.

Below jQuery scripts display the image in a modal.


<script>
  // To display image in modal
 $(document).on("click", ".view", function () {
  var path = "uploads/";
  var image = $(this).data('id');
  var str = '<img src="'+path+image+'">';
  $(".modal-body").html(str);   
  });

</script>

Let us see the entire application developed in CodeIgniter 3.

Create a table in MySQL database for user profiles

We will create a table named 'user_profile' in MySQL database. This table will have user user name, email and image. The table structure is given below:

Table: user_profile

This table stores details of all users.

CodeIgniter 3 dynamic image

Below are the columns in this table.

  1. id - Unique user id, primary key and auto incremented
  2. name - Name of the user
  3. email - Email of the user
  4. image - Image file name of the user

user_profile.sql


CREATE TABLE `user_profile` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `image` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user_profile` (`id`, `name`, `email`, `image`) VALUES
(1, 'Avatar1', 'avatar1@test.com', 'avatar1.png'),
(2, 'Avatar2', 'avatar2@test.com', 'avatar2.png'),
(3, 'Avatar3', 'avatar3@test.com', 'avatar3.png');

ALTER TABLE `user_profile`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `user_profile`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

We will be using a folder named 'userlist' under xampp/htdocs. So, the root directory will be xampp/htdocs/userlist.

Write Controller code (UserController.php)

We will have an index() method to get all users and load the view with the user data.

In the index() method, we call a model method named get_user() to get all the users from the database and load the view with the user data.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class UserController extends CI_Controller {
	function __construct() {
	    parent::__construct();
	    $this->load->model('ModelUser');
	}

	public function index(){
		$data['image_path'] = $this->config->item('image_file_path');
		$data['user_data'] = $this->ModelUser->get_user();
		$this->load->view('view_users',$data);
		}

}  // end of Controller class

Note that we have a folder named 'uploads' in our root directory. In this folder, all uploaded images are kept. So, we have defined image_file_path in application/config/config.php as below:


$config['image_file_path'] = 'uploads/';
$this->config->item('image_file_path') gives the image file path.

Write Model code (ModelUser.php)

get_user() method in the model:

application/models/ModelUser.php


<?php

class ModelUser extends CI_Model {

  function __construct() {
    parent::__construct();
  }

  function get_user() {
    $this->db->select('*');
    $this->db->from('user_profile');
    $query = $this->db->get();
    return $query->result();
  }

}

get_user() method selects all the users from the user_profile table.

Develop the view to display the users (view_users.php)

We will display a list of users with with images as given below:

Display image in modal jquery in CodeIgniter 3

It is a simple html table to display details of each user using a for-loop. When you click on a photo, it will be displayed in a modal. So, we will also define the modal in this view. Let's see the code:

application/views/view_users.php


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

<head>
  <title>Display Image in a Modal</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="<?php echo base_url('assets/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="<?php echo base_url('assets/js/modal.js') ?>"></script>
</head>

<body>
  <div class="container">
    <h1>User List</h1>
    <div class="table-responsive">
      <table class="table table-bordered table-stripe">
        <thead class="table-dark">
          <tr>
            <th>Serial No.</th>
            <th>Name</th>
            <th>Email</th>
            <th>Photo</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $counter = 0;
          if (!empty($user_data)) {
            foreach ($user_data as $row) {
              $counter++ ?>
              <tr>
                <td><?php echo $counter; ?>
                <td><?php echo $row->name; ?></td>
                <td><?php echo $row->email; ?></td>
                <td>
                  <a href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#showImg" class="view" data-id="<?php echo $row->image; ?>">
                    <img class="photo" alt="Profile Photo" src="<?php echo base_url() . $image_path . $row->image; ?>" title="View Photo" />
                  </a>
                </td>
              </tr>
            <?php }
          } else { ?>
            <tr>
              <td colspan="4">No Users found</td>
            </tr>
          <?php } ?>
        </tbody>
      </table>
    </div>
  </div>
  <!-- Modal to display the image -->
  <div id="showImg" 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 image 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>

Look at the last column of the table which is the Photo. Here, a modal is called with the value $row->image using data-id attribute.

There is a custom stylesheet used in the views. It is given below:


*{
  box-sizing: border-box;
}
h1{ 
  text-align: center;
}
.photo{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.table{
    width: 60%;
    margin:auto;
    text-align: center;
}

.modal-body img{
    width:100%;
    height: auto;
}

Write jQuery script to display photo in modal

jQuery script takes the parameter value sent to the modal and creates an <img> element with source as the image file name. Then it displays the image in a Bootstrap modal. Let's see the code below:


<script>
      // To display image in modal
     $(document).on("click", ".view", function () {
      var path = "uploads/";
      var image = $(this).data('id');
      var str = '<img src="'+path+image+'">';
      $(".modal-body").html(str);   
      });
</script>

It creates an <img> element with the source as the image name with an upload path. The <img> element is written in the modal body.

Update Configuration files

  1. Update config file (application/config/config.php) to add 'image_file_path' for the image path. Set 'base_url' and 'index_page' as below in this file:

    
    $config['base_url'] = 'http://localhost/userlist/';
    $config['image_file_path'] = 'uploads/';
    
    
    $config['index_page'] = '';
    
  2. Update database name, userid and password in application/config/database.php.

  3. Update routes file (application/config/routes.php) as below:
      
    $route['default_controller'] = 'UserController';
    $route['404_override'] = '';
    $route['translate_uri_dashes'] = FALSE;
    
  4. Also, update .htaccess file to remove index.php from the URL. It is in the root folder which is xampp/htdocs/userlist.

    
    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
    

Test The Application

Run localhost/userlist in the browser. You will see the users are displayed as below:

how to display dynamic image in modal

You can see users are displayed with their photos. Click on a photo of any user, the photo will be displayed in a modal. See below when I clicked on one of the photos:

onclick image popup jquery

Show an image in modal pop upConclusion

In this tutorial, we explored how to display dynamic images in a modal using CodeIgniter 3 and jQuery. You learned how to fetch image data from the database, load it dynamically and display it inside a responsive Bootstrap modal.

Please write your comments/questions in the Comments section below. Your questions, doubts and suggestions are always welcome.

Post a Comment

Save my Name and Email id for future comments