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!
View data in a Bootstrap modal using Ajax, jQuery and PHP
Reviewed by DAL
on
January 30, 2018
Rating:
No comments: