View data in a Bootstrap modal using Ajax, jQuery and PHP
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
Create a database called fetch_ajax and import the SQL file I have included in my GitHub repository called fetch_ajax.sql.
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.
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">×</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!
62 Comments
Keren mas tutorialnya sangat bermanfaat.
ReplyDeletetell me in English plz :D
DeleteIts help full thx.
ReplyDeleteThanx :D
DeletePlease make tutorial CRUD ajax plus view like this. Thanks
ReplyDeleteOk. I'll try to do it :D
DeletePkDomain (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.
ReplyDeleteThank you.Well it was nice post and very helpful information on Ruby on Rails Online Course India
ReplyDeleteThanx Teju!
DeleteGreat content really helped me
ReplyDeleteThanx apana!
Deletein my case i did same in my project but view info is not showing popup ... can you tell me why.
ReplyDeleteI can not tell exactly.. check your code again.. :D or post here
Deletehello sir!
ReplyDeletei 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.
Without looking at code, I can not tell exactly.. That's the problem!
Deletei 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
Deletedie(print_r($row,TRUE)); but after it i printed $row["ram"]; . result was empty
I just checked the code again.. it's working perfect.. I mean my GitHub code.. https://github.com/SalithaUCSC/Bootstrap-Modal-fetch
Deletei have 200 data.
ReplyDeletebut just 10 data can call that view modal
for data 11 - 200 cant call that view modal
can you tell me that why?
#ThanksAlotBefore
$('.view_data').click(function()
ReplyDeletethat 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
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.
Deletepublic function view_migrasi(){
Delete$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()... ]?
do you have 200 records in database?
Deleteyes sir.
Deletei 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
it should work without considering the count.
Deletesure. but i try use same as with your example code, still cant.
Deleteonly 10 records phone can call $('.view_data').click(function().
can u help me with this issues?
I found that you are correct. It's not working with pagination.. I will try to fix this and send u the code
DeleteHey! 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!
Deletehttps://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...
ok nice try.
Deletethanks alot before sir.
It's ok..Thanx again.. Readers' comments are the precious things for blogger :D
DeleteExcellent tutorial, what I was looking for
ReplyDeleteThank You! Pleasure to me!
DeleteI would like to thank this blog admin for sharing this worthy information with us. Keep doing more.
ReplyDeleteEnglish Speaking Classes in Mumbai
English Speaking Course in Mumbai
Best English Speaking Classes in Mumbai
Spoken English Classes in Mumbai
English Classes in Mumbai
English Speaking Classes in Mulund
Thanks ruhi for encouraging me! Keep in touch with TechPool..I will post more..
DeleteThan ruhi for encouraging me! Keep in touch with TechPool..
ReplyDeleteThe blog you have posted is more informative... Thanks for your valid blog.
ReplyDeleteSelenium Training in Bangalore
Selenium Training in Coimbatore
Best Selenium Training Institute in Bangalore
best selenium training in coimbatore
RPA training in bangalore
Selenium Training in Bangalore
Java Training in Madurai
Oracle Training in Coimbatore
PHP Training in Coimbatore
Thanx Riya for your feedback..It's a pleasure to hear your comment..
DeleteThanx jenifer for your comment!
ReplyDeleteThe best Blog!!! Thanks for sharing with us... Waiting for your new updates.
ReplyDeleteOracle Training in Coimbatore
best oracle training institute in Coimbatore
Cloud Computing Courses in Coimbatore
cloud computing training in coimbatore
Best Java Training Institutes in Bangalore
Hadoop Training in Bangalore
Data Science Courses in Bangalore
Thank you very much Shadeep Shree! Looking more into JS now..keep in touch!
Deletewhy modal can't be opened?
ReplyDeleteit should be opened if you have carefully followed the steps! have you linked jquery to the view file?
Delete
ReplyDeleteNice 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
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!
DeleteYo bro, nice tutorial, love it
ReplyDeleteThanx bro!
DeleteThank you Amit!
ReplyDeleteHeloo, 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.
ReplyDeleteHi Ramanda, did you look at your console? any error logging to the console?
Deletethank you very much for the feedback :D
ReplyDeleteNice post i get inspired from this article and this is very interesting. oracle training in chennai
ReplyDeleteThank you!
Deletehey 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
ReplyDeletepublic 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
Solved. i forgor if i have 2 return so i remove the first return. thanks for the tutor.
DeleteThank you!
ReplyDeletethank you for the feedback
ReplyDeleteThank you for sharing this amazing post. Looking forward to reading more.
ReplyDeleteBest Web Design and Development Company in Delhi
you're welcome Ankita :D
Deletethanks 👍
ReplyDeletethanks for reading 🙂
ReplyDeletebut sir error for me as in modal function
ReplyDeleteNice Blog. Thanks for sharing with us.
ReplyDeleteWeb Designing Company in Chennai
SEO Services
Digital Marketing Company in Chennai
Mobile App Development
Great and I have a nifty present: How To Renovate House Exterior house remodel before and after
ReplyDelete