Hello guys! what's up? I'm here with another tutorial based on Ajax and jQuery.. Ready to go? First I can give you a short description about today's article. I think all of you are aware of Bootstrap as guys interested in web development field. Bootstrap is the most popular CSS framework in wed designing. Recently its latest version has been released; version 4. But still it's not a stable version and still in developing stage. But Bootstrap 3.3.7 is a very decent and strong version which is going to be used today for this article. I'm going to display details of each record in database in a Bootstrap modal component. Here you can watch a short video clip to get the abstract idea of what will you learn today...


As we did before download Codeigniter and make a project folder..Then prepare the essential configurations for a Codeigniter project. If you are not aware of it, vist the below link to get an idea.

Essential-configurations-to-start-codeigniter-project

Download Source Code from here : Bootstrap-Modal-fetch

Configurations

Project folder => FecthAjax
Base URL => $config['base_url'] = 'http://localhost/FecthModal
Database name => fetch_ajax
Database table name => phones
Autoload libraries => database
Autoload helpers => form , url
Default Controller => Phone

Create a database called fetch_ajax and import the SQL file I have included in my GitHub repository called fetch_ajax.sql.

Let's start the work...

First I will create the model file to fetch data from database. In my case model is named as Phone_model. It contains 2 functions. One is to fetch add phones stored in database and the other one to get the phone for the Bootstrap modal. This is the code.

Phone_model.php


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Phone_model extends CI_Model {
 // function to fetch all phone
 public function get_phones()
 {
     $this->db->select('*');
     $this->db->order_by('phone_id','DESC');
     $query = $this->db->get('phones');
     return $query->result();
 }
 // function that finds the phone by its ID to display in th Bootstrap modal
 public function get_search_phone($phoneData)
 {
  $this->db->select('*');
  $this->db->where('phone_id',$phoneData);
  $res2 = $this->db->get('phones');
  return $res2;
 }
}

Now we are going to create the controller file to pass the data to the views.

Phone.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Phone extends CI_Controller {
 public function __construct()
 {
  parent::__construct();
  $this->load->model('Phone_model');
 }
 public function index()
 {
  $data['allphones'] = $this->Phone_model->get_phones();
  $this->load->view('phone_view',$data);
 }
 public function get_phone_result()
 {
 }
You can see, still the second function is not implemented. Before it, we have to create the view file. I have named it as phone_view. Let's go for it.

phone_view.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Bootstrap Modal with Ajax</title>
 <!-- Bootstrap CSS CDN -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
 <!-- DataTables CSS CDN -->
 <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css">
 <!-- Font Awesome CSS CDN -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
 <div class="container">
  <h2 class="text-center" style="margin-top: 30px;">View Data in Bootstrap Modal using Codeigniter, jQuery and Ajax</h2>
  <br><br>
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title"><i class="fa fa-database" aria-hidden="true"></i> Stored Phones in Database</h3>
    </div>
    <div class="panel-body">
   <div class="table-responsive">
           <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
             <thead>
               <tr >
                 <th>Phone</th>
                 <th>Phone Name</th>
                 <th>Internal Memory</th>
                 <th>RAM</th>
                 <th>Price LKR</th>
                 <th class="text-center">Details</th>                          
               </tr>
             </thead>
             <tbody>
               <?php foreach ($allphones as $row) : ?>
               <tr>
                 <td><center><img style="width:50px; height: 60px;" src="<?php echo base_url();?>assets/images/<?php echo $row->image1; ?>" class="thumbnail"></center></td>
                 <td><?php echo $row->name ?></td>
                 <td><?php echo $row->internal ?></td>
                 <td><?php echo $row->ram ?></td>
                 <td><?php echo $row->price ?></td>
                 <td><center><input type="button" class="btn btn-info btn-sm view_data" value="View Info" id="<?php echo $row->phone_id; ?>"></center></td>
               </tr>
               <?php endforeach; ?>
             </tbody>            
           </table>
    </div>
  </div>
 </div>
 <!-- view Modal -->
 <div class="modal fade" id="phoneModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true" style="margin-top: -20px;">
   <div class="modal-dialog modal-lg">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
         <h4 class="modal-title" id="myModalLabel">Phone Details</h4>
       </div>
       <div class="modal-body">
        <!-- Place to print the fetched phone -->
         <div id="phone_result"></div>
       </div>
       <div class="modal-footer">
         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
       </div>
     </div>
   </div>
 </div>
 <!-- jQuery JS CDN -->
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> 
 <!-- jQuery DataTables JS CDN -->
 <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
 <!-- Bootstrap JS CDN -->
 <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
 <!-- Bootstrap JS CDN -->
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> 
    <script type="text/javascript">
     // Start jQuery function after page is loaded
        $(document).ready(function(){
         // Initiate DataTable function comes with plugin
         $('#dataTable').DataTable();
         // Start jQuery click function to view Bootstrap modal when view info button is clicked
            $('.view_data').click(function(){
             // Get the id of selected phone and assign it in a variable called phoneData
                var phoneData = $(this).attr('id');
                // Start AJAX function
                $.ajax({
                 // Path for controller function which fetches selected phone data
                    url: "<?php echo base_url() ?>Phone/get_phone_result",
                    // Method of getting data
                    method: "POST",
                    // Data is sent to the server
                    data: {phoneData:phoneData},
                    // Callback function that is executed after data is successfully sent and recieved
                    success: function(data){
                     // Print the fetched data of the selected phone in the section called #phone_result 
                     // within the Bootstrap modal
                        $('#phone_result').html(data);
                        // Display the Bootstrap modal
                        $('#phoneModal').modal('show');
                    }
             });
             // End AJAX function
         });
     });  
    </script>
</body>
</html>

Waiting for Ajax and jQuery part? Here it appears...!

First I have included the phone details in a table to show in a proper format. For our ease, I always use jQuery DataTable plugin to implement the table with sorting and searching functionalities.
$('#dataTable').DataTable();  =>  does the job for you.. dataTable is the ID of the table. Then the logic for the button should be included. It should ope up a modal when get clicked and display the data of a particular phone ID.

View info button has been given a class called view_data. So now, jQuery click function is executed to load the modal using this button class. Carefully look at the line where I have included the view button. You can see I have given it an ID with the value of each phone's ID. ID is the sttribute. That's why we use attr(). Now we get this ID value and store it in a variable called phoneData

Here AJAX joins the party!!! An Ajax request is sent to the server with data called phoneData. If data is processed correctly then callback function should be executed(success function). URL for fetching the selected phone is the controller path. Now I'm going to write the second function of the controller. If it founds a result, then it will be printed on the Bootstrap modal; within the section called phone_result. The results should be echoed through the controller function. Now we can implement the function for this task in controller file.


 public function get_phone_result()
 {
        $phoneData = $this->input->post('phoneData');
        if(isset($phoneData) and !empty($phoneData)){
            $records = $this->Phone_model->get_search_phone($phoneData);
            $output = '';
            foreach($records->result_array() as $row){
             $output .= '      
         <h4 class="text-center">'.$row["name"].'</h4><br>
         <center><img style="width:150px; height: 160px;" src="'.base_url().'assets/images/'.$row["image1"].'"></center><br><br>
         <div class="row">
         <div class="col-lg-6">
          <table class="table table-bordered">
           <tr>
            <td><b>RAM</b></td>
            <td>'.$row["ram"].'</td>
           </tr>
           <tr>
            <td><b>Memory</b></td>
            <td>'.$row["internal"].'</td>            
           </tr>            
           <tr>
            <td><b>Back Camera</b></td>
            <td>'.$row["cam_primary"].'</td>            
           </tr> 
           <tr>
            <td><b>Front Camera</b></td>
            <td>'.$row["cam_secondary"].'</td>            
           </tr>
           <tr>
            <td><b>Display Type</b></td>
            <td>'.$row['display_type'].'</td>            
           </tr>             
           <tr>
            <td><b>Display Size</b></td>
            <td>'.$row['display_size'].'</td>            
           </tr>
           <tr>
            <td><b>Resolution</b></td>
            <td>'.$row["resolution"].'</td>
           </tr>                        
           <tr>
            <td><b>OS</b></td>
            <td>'.$row["os"].'</td>            
           </tr>                        
       </table>
      </div>
      <div class="col-lg-6">
       <table class="table table-bordered">
           <tr>
            <td><b>Dimensions</b></td>
            <td>'.$row["dimension"].'</td>
           </tr>                        
           <tr>
            <td><b>SIM Type</b></td>
            <td>'.$row["sim"].'</td>            
           </tr>                                           
           <tr>
            <td><b>Chipset</b></td>
            <td>'.$row["chipset"].'</td>            
           </tr> 
           <tr>
            <td><b>CPU</b></td>
            <td>'.$row["cpu"].'</td>            
           </tr> 
           <tr>
            <td><b>GPU</b></td>
            <td>'.$row['gpu'].'</td>            
           </tr> 
           <tr>
            <td><b>Card Slot</b></td>
            <td>'.$row["cardslot"].'</td>
           </tr>                        
           <tr>
            <td><b>Battery</b></td>
            <td>'.$row["battery"].'</td>
           </tr>
           <tr>
            <td><b>Price</b></td>
            <td>Rs.'.$row["price"].'</td>
           </tr>                                  
       </table>       
      </div>
      </div>';
            }    
            echo $output;
        }
        else {
         echo '<center><ul class="list-group"><li class="list-group-item">'.'Select a Phone'.'</li></ul></center>';
        }
 }

Add this function to the controller we did not completed before. This function prints the phone details using a foreach loop. If you followed me, now you have the application! Enjoy it guys..This is the beauty of Ajax and jQuery...I'm also still learning these two. I'm very interested. I think you will also like them.


I'm going to wrap up the session guys! If you want to know something, drop a comment. And don't forget to like my Facebook page; TechPool..
Thank You!




61 Comments

  1. Keren mas tutorialnya sangat bermanfaat.

    ReplyDelete
  2. Its help full thx.

    ReplyDelete
  3. Please make tutorial CRUD ajax plus view like this. Thanks

    ReplyDelete
  4. PkDomain (PVT) Limited is a provider of Shared, Reseller, VPS and Dedicated Web hosting, Web Designing & Development in all over Pakistan. Privately held and based in San Francisco, California, USA, the company was founded in 2002 by young entrepreneur.The Company is also providing Surveillance services all over Pakistan from 2012. You can check latest prices and packages on www.pkdomain.com.pk. The Company has also setup its International offices in various countries all over the world and maintaining web hosting servers from San Francisco, California.

    ReplyDelete
  5. Thank you.Well it was nice post and very helpful information on Ruby on Rails Online Course India

    ReplyDelete
  6. Great content really helped me

    ReplyDelete
  7. in my case i did same in my project but view info is not showing popup ... can you tell me why.

    ReplyDelete
    Replies
    1. I can not tell exactly.. check your code again.. :D or post here

      Delete
  8. hello sir!
    i copied your code. And try to get data from database into bootstrap modal but data is not getting.
    i think problem is in controller $outPut variable . Cz when i checked out foreach loop variable $row like this. pre tag(pre tag not alowed in this comment) and die(print_r($row,TRUE)); data is printed on screen . Can u help me how to display data with $outPut variable or with alternate method.

    ReplyDelete
    Replies
    1. Without looking at code, I can not tell exactly.. That's the problem!

      Delete
    2. i copied your all to all code for practice. and checked out it. it is running except $outPut array in get_phone_result() function in controller. in foreach loop $row worked. it print all data with pre tag
      die(print_r($row,TRUE)); but after it i printed $row["ram"]; . result was empty

      Delete
    3. I just checked the code again.. it's working perfect.. I mean my GitHub code.. https://github.com/SalithaUCSC/Bootstrap-Modal-fetch

      Delete
  9. i have 200 data.
    but just 10 data can call that view modal
    for data 11 - 200 cant call that view modal
    can you tell me that why?

    #ThanksAlotBefore

    ReplyDelete
  10. $('.view_data').click(function()

    that code not work for data number 11 - end data.

    even click just work for data number 1 - 10.

    please, can you tell me why?

    #Thanks alot before

    ReplyDelete
    Replies
    1. Have you included pagination in your model? O you tried to load all 200 data into modal window at once? if so, there will be an issue with click function.

      Delete
    2. public function view_migrasi(){
      $data['allmigrasi'] = $this->m_migrasi->get_migrasi();
      $this->load->view('lihat_data',$data);
      }

      ##### Controller #####

      public function get_migrasi(){
      $this->db->select('*');
      $this->db->order_by('id_mig','ASC');
      $query = $this->db->get('migrasi');
      return $query->result();
      }

      ##### Model #####

      for view.php same as your code.

      what u'r mean, include pagination to my model [ public function get_migrasi()... ]?

      Delete
    3. yes sir.
      i have 200 records.
      but only 10 records can call $('.view_data').click(function()
      for another records cant call $('.view_data').click(function()

      what is the solution for that issue?

      #Thanks

      Delete
    4. it should work without considering the count.

      Delete
    5. sure. but i try use same as with your example code, still cant.
      only 10 records phone can call $('.view_data').click(function().

      can u help me with this issues?

      Delete
    6. I found that you are correct. It's not working with pagination.. I will try to fix this and send u the code

      Delete
    7. Hey! Try this snippet.. We have to change the script adding event to the data table.. You can find the script here.. I have created a Gist for you!
      https://gist.github.com/SalithaUCSC/e19d4fbec18a479368695f6c504b2cce

      I updated the GitHub source code also..You can check!
      Thanx for informing me.. Actually I had not checked it before...

      Delete
    8. ok nice try.
      thanks alot before sir.

      Delete
    9. It's ok..Thanx again.. Readers' comments are the precious things for blogger :D

      Delete
  11. Excellent tutorial, what I was looking for

    ReplyDelete
  12. Replies
    1. Thanks ruhi for encouraging me! Keep in touch with TechPool..I will post more..

      Delete
  13. Than ruhi for encouraging me! Keep in touch with TechPool..

    ReplyDelete
  14. Replies
    1. Thanx Riya for your feedback..It's a pleasure to hear your comment..

      Delete
  15. Replies
    1. Thank you very much Shadeep Shree! Looking more into JS now..keep in touch!

      Delete
  16. Replies
    1. it should be opened if you have carefully followed the steps! have you linked jquery to the view file?

      Delete

  17. Nice blog.That is very interesting; you are a very skilled blogger. I have shared your website in my social networks! A very nice guide.
    low cost web designing
    best web designers in hyderabad

    ReplyDelete
    Replies
    1. Thank you very much Nandhini! Your comment is so much courageous! I will keep you updated with more technologies..Join with my other article categories also!

      Delete
  18. Yo bro, nice tutorial, love it

    ReplyDelete
  19. Heloo, can you help me? I literally copy your code into my project, but idk, why it doesnt run. The modal is show, but without the data.

    ReplyDelete
    Replies
    1. Hi Ramanda, did you look at your console? any error logging to the console?

      Delete
  20. thank you very much for the feedback :D

    ReplyDelete
  21. Nice post i get inspired from this article and this is very interesting. oracle training in chennai

    ReplyDelete
  22. hey sir, i want to use tutorial, but i have problem i cant get data cause my table is joined with another table, can u help me ? heres my code of my model and implement by ur code
    public function get_search($phoneData)
    {
    $this->db->select('*');
    return $this->db->from('device')
    ->join('alternatif', 'alternatif.id_a=device.id_a')
    ->where('device.id_d',$phoneData);
    $res2 = $this->db->get();
    return $res2;
    }
    pls help meh

    ReplyDelete
    Replies
    1. Solved. i forgor if i have 2 return so i remove the first return. thanks for the tutor.

      Delete
  23. Thank you for sharing this amazing post. Looking forward to reading more.
    Best Web Design and Development Company in Delhi

    ReplyDelete
  24. but sir error for me as in modal function

    ReplyDelete