Read Also : Bootstrap Signup Form Design with Validations
Read Also : [ Updated ] Ajax Form Submit without Page Refresh using jQuery in PHP
Database Design/Table
this is our database design with members table containing some dumping data, this will be shown in bootstrap modal dynamically.
--
-- Database: `dbtest`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_members`
--
CREATE TABLE IF NOT EXISTS `tbl_members` (
`user_id` int(5) NOT NULL AUTO_INCREMENT,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
`email` varchar(50) NOT NULL,
`position` varchar(25) NOT NULL,
`office` varchar(25) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `tbl_members`
--
INSERT INTO `tbl_members` (`user_id`, `first_name`, `last_name`, `email`, `position`, `office`) VALUES
(1, 'Ashton', 'Bradshaw', '[email protected]', 'Software Engineer', 'Florida'),
(2, 'Garrett', 'Winters', '[email protected]', 'Sales Assistant', 'Singapore'),
(3, 'Jackson', 'Silva', '[email protected]', 'Support Engineer', 'New York'),
(4, 'Jenette', 'Caldwell', '[email protected]', 'Director', 'London'),
(5, 'Rhona', 'Walton', '[email protected]', 'System Architect', 'San Francisco');
Connect to Database
this is database connection file queried with PDO extensiion so copy the following code and create a new file as dbconfig.php then paste the copied below code inside the file.
<?php
$DBhost = "localhost";
$DBuser = "root";
$DBpass = "";
$DBname = "dbtest";
try {
$DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex){
die($ex->getMessage());
}
Showing the Data
this is a simple code which will select data from members table and show them in html table and view button contains three data attributes data-toggle=”modal” which toggles the modal on click event, data-target=”#view-modal” it will open a targeted modal which contains view-modal id, and the last attribute is data-id=”<?php echo $row[‘user_id’]; ?>” which has id of users and it will help to pass id to another page via ajax.
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Full Name</th>
<th>View Profile</th>
</tr>
</thead>
<tbody>
<?php
require_once 'dbconfig.php';
$query = "SELECT * FROM tbl_members";
$stmt = $DBcon->prepare( $query );
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $row['first_name']." ".$row['last_name']; ?></td>
<td>
<button data-toggle="modal" data-target="#view-modal" data-id="<?php echo $row['user_id']; ?>" id="getUser" class="btn btn-sm btn-info"><i class="glyphicon glyphicon-eye-open"></i> View</button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
it will looks like this :
as you can see every row has a view button and when any of button will get clicked a popup modal will be displayed with particular clicked row with full row detail in bootstrap modal dynamically.
button has a id=”getUser” attribute and whenever it get clicked a popup modal will be appeared with mysql data of that particular id(row).
Bootstrap Modal : Ajax HTML Response
this is bootstrap modal code which has id=”view-modal” attribute tha target id of data-target=”#view-modal” attribute and whenever button will click the following modal will popup with the particular row with full details in table format. and the response from server will be loaded in id=”dynamic-content” within modal body class and the response will be in HTML Format.
<div id="view-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<i class="glyphicon glyphicon-user"></i> User Profile
</h4>
</div>
<div class="modal-body">
<div id="modal-loader" style="display: none; text-align: center;">
<!-- ajax loader -->
<img src="ajax-loader.gif">
</div>
<!-- mysql data will be load here -->
<div id="dynamic-content"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Ajax Request : dataType – HTML
below is the simple ajax() call which is responsible to make bootstrap modal dynamic. $(this).data(‘id’) holds id in uid variable and send it to “getuser.php” with HTTP POST request and returns the response in HTML format, you can see the request has dataType: ‘html’ and once request is done data will be returned and will be displayed in $(‘#dynamic-content’).html(data);, that’s it.
$(document).ready(function(){
$(document).on('click', '#getUser', function(e){
e.preventDefault();
var uid = $(this).data('id'); // get id of clicked row
$('#dynamic-content').html(''); // leave this div blank
$('#modal-loader').show(); // load ajax loader on button click
$.ajax({
url: 'getuser.php',
type: 'POST',
data: 'id='+uid,
dataType: 'html'
})
.done(function(data){
console.log(data);
$('#dynamic-content').html(''); // blank before load.
$('#dynamic-content').html(data); // load here
$('#modal-loader').hide(); // hide loader
})
.fail(function(){
$('#dynamic-content').html('<i class="glyphicon glyphicon-info-sign"></i> Something went wrong, Please try again...');
$('#modal-loader').hide();
});
});
});
getuser.php : for HTML dataType
this file will called silently in back-end via ajax to fill out bootstrap modal whichever id were requested and the table will be displayed in bootstrap modals $(‘#dynamic-content’) div.
<?php
require_once 'dbconfig.php';
if (isset($_REQUEST['id'])) {
$id = intval($_REQUEST['id']);
$query = "SELECT * FROM tbl_members WHERE user_id=:id";
$stmt = $DBcon->prepare( $query );
$stmt->execute(array(':id'=>$id));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
?>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<th>First Name</th>
<td><?php echo $first_name; ?></td>
</tr>
<tr>
<th>Last Name</th>
<td><?php echo $last_name; ?></td>
</tr>
<tr>
<th>Email ID</th>
<td><?php echo $email; ?></td>
</tr>
<tr>
<th>Position</th>
<td><?php echo $position; ?></td>
</tr>
<tr>
<th>Office</th>
<td><?php echo $office; ?></td>
</tr>
</table>
</div>
<?php
}
ok, we have just seen ajax request with html datatype now we will see ajax request with json datatype, let’s fill modal with json data.
Bootstrap Modal : Ajax JSON Response
this bootstrap modal contains empty table within class=”modal-body” you can see below. and every row has named placeholder as an id so it will be filled out by ajax json response, have a look.
<div id="view-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<i class="glyphicon glyphicon-user"></i> User Profile
</h4>
</div>
<div class="modal-body">
<div id="modal-loader" style="display: none; text-align: center;">
<img src="ajax-loader.gif">
</div>
<div id="dynamic-content"> <!-- mysql data will load in table -->
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<th>First Name</th>
<td id="txt_fname"></td>
</tr>
<tr>
<th>Last Name</th>
<td id="txt_lname"></td>
</tr>
<tr>
<th>Email ID</th>
<td id="txt_email"></td>
</tr>
<tr>
<th>Position</th>
<td id="txt_position"></td>
</tr>
<tr>
<th>Office</th>
<td id="txt_office"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Ajax Request : dataType – JSON
i hope it’s not confusing you, as i said bootstrap modal contains empty table with named placeholders as an id, so the following ajax call makes it dynamic by placing json data in table. like id=”txt_fname” this will be placed by json $(‘#txt_fname’).html(data.first_name); that’s it.
$(document).ready(function(){
$(document).on('click', '#getUser', function(e){
e.preventDefault();
var uid = $(this).data('id'); // get id of clicked row
$('#dynamic-content').hide(); // hide dive for loader
$('#modal-loader').show(); // load ajax loader
$.ajax({
url: 'getuser.php',
type: 'POST',
data: 'id='+uid,
dataType: 'json'
})
.done(function(data){
console.log(data);
$('#dynamic-content').hide(); // hide dynamic div
$('#dynamic-content').show(); // show dynamic div
$('#txt_fname').html(data.first_name);
$('#txt_lname').html(data.last_name);
$('#txt_email').html(data.email);
$('#txt_position').html(data.position);
$('#txt_office').html(data.office);
$('#modal-loader').hide(); // hide ajax loader
})
.fail(function(){
$('.modal-body').html('<i class="glyphicon glyphicon-info-sign"></i> Something went wrong, Please try again...');
});
});
});
getuser.php : for JSON dataType
this file will get requested by the above ajax call and returns response in json format, json_encode(; function makes easy to convert rows into json format.
<?php
header('Content-type: application/json; charset=UTF-8');
require_once 'dbconfig.php';
if (isset($_POST['id']) && !empty($_POST['id'])) {
$id = intval($_POST['id']);
$query = "SELECT * FROM tbl_members WHERE user_id=:id";
$stmt = $DBcon->prepare( $query );
$stmt->execute(array(':id'=>$id));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
exit;
}
This is how it looks :
all done, if you click any button to see individual’s profile just to click on that button then our modal will be looks like this with MySQL data via ajax request.
Ok, We have just covered here simple yet useful script about showing data from mysql dynamically in bootstrap modal with the help of ajax, both response datatypes, hope you guys like this tutorial, and please don’t forget to share it, if you like it then just share it, and feel free to ask any queries about any of tutorial.
That’s it.