How to Display Dynamic Image in a Modal in CodeIgniter 3

In this topic, we will show how to dynamically display a photo in a bootstrap modal using jQuery with CodeIgniter 3 and MySQL. We will create a simple application in CodeIgniter 3 to display a list of users with their photos. When you click on a photo, a larger size of the photo will be popped up. You will learn how to display data from the database in an html table andshow the modal image using jQuery.

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-toggle="modal" data-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 photo, 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 details, - user name, email and image. The table structure is given below:

Table: user_profile

This table stores details of all users.

bootstrap modal 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;

Folder Structure

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 and here we are using it in line 11 above. $this->config->item('image_file_path') gives the image file path from config.php and it is defined as below:


$config['image_file_path'] = 'uploads/';

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)

The view displays the list of users with links to view the photo of each user. Below is a list of users displayed.

display image in modal jquery

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

application/views/view_users.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>User List</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="<?php echo base_url('assets/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="<?php echo base_url('assets/js/modal.js') ?>"></script>
</head>
<body>
  <div class="container">
    <h3>User List</h3>
      <div class="table-responsive">
        <table>
          <tr>
            <thead>
              <th>Serial No.</th><th>Name</th><th>Email</th><th>Photo</th>
            </thead>
          </tr>
          <?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-toggle="modal" data-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="7">No Users found</td></tr>
          <?php } ?>
        </table>
      </div>
      <!-- Modal to display the image -->
      <div id="showImg" class="modal fade profile" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
          </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>

Look at the last column of the table which is the Photo. Here a modal is called (this modal is defined later). A parameter $row->image is sent to the modal using a data-id attribute.

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

assets/css/style.css


h3{
  margin-top: 20px;
  text-align: center;
}
.photo{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
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;
}
.profile .modal-body{
  overflow-y:auto;
}
.modal-dialog .modal-header {
  display:block;
}
.modal-dialog{
  max-width: 650px;
}
.modal-body img{
  width:100%;
}

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 and Test the Application

Let us now update few setup files before we run the application.

  1. Update autoload.php (application/config/autoload.php)
    
    $autoload['libraries'] = array('database');
    
    
    $autoload['helper'] = array('url');
    

    Also, 'url' is added in the helper array.

  2. 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'] = '';
    
  3. Update database setup file (application/config/database.php) to use database name, userid and password as below:

    
    $active_group = 'default';
    $query_builder = TRUE;
    
    $db['default'] = array(
    	'dsn'	=> '',
    	'hostname' => 'localhost',
    	'username' => 'root',
    	'password' => '',
    	'database' => 'demo',
    	'dbdriver' => 'mysqli',
    	'dbprefix' => '',
    	'pconnect' => FALSE,
    	'db_debug' => (ENVIRONMENT !== 'production'),
    	'cache_on' => FALSE,
    	'cachedir' => '',
    	'char_set' => 'utf8',
    	'dbcollat' => 'utf8_general_ci',
    	'swap_pre' => '',
    	'encrypt' => FALSE,
    	'compress' => FALSE,
    	'stricton' => FALSE,
    	'failover' => array(),
    	'save_queries' => TRUE
    );
    
  4. Update routes file (application/config/routes.php) as below:
      
    $route['default_controller'] = 'UserController';
    $route['404_override'] = '';
    $route['translate_uri_dashes'] = FALSE;
    
  5. Update .htaccess (hypertext access) 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 along 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

I show an image in modal pop upConclusion

In this example, we have seen how to display a photo in a modal in CodeIgniter 3 dynamically by selecting data from the database. We have used a photo here to display in the modal, but you can use it for any similar requirement, like you can display some data in a modal when the user clicks on a button or a link, by passing a parameter to the modal.

Post a Comment

Save my Name and Email id for future comments