Hello friends, in this tutorial we will see How to Show Dynamic MySQL Data in Bootstrap Modal, Well Modals are become very popular and important UI for any kind of websites and with Modals we can do lot’s of things, nowadays Modals are mostly used for add, update and delete even for display dynamic contents and you also might have seen login/signup popup modals in some websites, and we have also covered a tutorial on deleting mysql rows with bootstrap confirm modal(dialog) with the help of bootbox, we can also create the same without using any plugin, and now here in this tutorial i will show how you can easily display/show mysql data in bootstrap modal and the mysql rows are displayed dynamically in modal via ajax call, check the demo of this tutorial and see how it looks.
Read Also : Bootstrap Signup Form Design with Validations
Read Also : [ Updated ] Ajax Form Submit without Page Refresh using jQuery in PHP
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).
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.
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.
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.
data not shoqing inside modal window for both html type and json type
ReplyDeleteHello Saurabh, what kind of error you are getting, do let me know ..
DeleteWow Pradeep Khodke,
ReplyDeleteThanks for this awesome tutorial...
You're welcome, Vinay :)
Deletedo you have working code
DeleteGreat stuff Pradeed, keep up the good work
ReplyDeleteThanks Emmanuel... :)
DeleteHi Pradeep,
ReplyDeleteThis line of code doesn't seem to work in my end. What's wrong with it?
data-id=""
P.S. I have the correct column name and name for the array.
Hi Shaun
Deleteyou can also use => attr("data-id") to get the id of row, but if you are using newer version of jquery then you should use => data("id")
Hey Pradeep! My bad! I was joining tables and I forgot to assign a name for the column that I was calling. I have a question regarding phpmailer. I deployed a project using phpmailer, and once I got it live, the emailing feature doesn't seem to work anymore. I tried debugging it offline, and everything seems fine. Any thoughts?
DeleteHey Shaun, now you can download the code, please download and try ...
DeleteFigured it out now. Thanks a lot Pradeep! Keep doing things like these. You make the world a better place! :D
DeleteHey Shaun, please make sure that phpmailer class is included properly or not and also try to debug like this
Delete$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
so that you can get idea about whats happening while sending email, and if you have domain smtp then you shoud use domain smtp credentials...
if you are still getting error then do let me know....
Hey Pradeep, got to fix the issue by commenting this line of code before I publish it "$mail->IsSMTP();". Do you know what's the issue with it? I know it fixed the issue, but I just want to know the reason. Thanks a lot!
DeleteGood job btw!
ReplyDeleteThanks...
Deletecan't download. i already subscribe
ReplyDeletehey zi, you can download the code...
DeleteTHANKS pradeep. can you make a tutorial about mysql edit,delete,search,filter combine together?
DeleteThanks for this tutorial.
ReplyDeleteHi Pradeep,
ReplyDeletecan't download it . i already subscribe like Zi did
Hi Pradeep,
ReplyDeletecan't download it. i already subscribe like Zi did
good)
ReplyDeleteHola Yo estoy tengo una subscripción a su pagina pero no puedo descargar el script. Que puedo hacer? Gracias.
ReplyDeleteHi, it seems dropbox download link is broken, I cannot access to it.
ReplyDeleteTried on other PC, MAC still did not work.
Is it only me not working? :<
Wow that's great i want it :)
ReplyDeletehave a look please www.subkuchsell.com
please suggest me for this kind of website www.subkuchsell.com
ReplyDeleteI am proud of you, I am now solving one of issue using your tutorial, I will bring back feedback
ReplyDeleteHello, Mr Pradeep..can you help me, I want to display registered user profiles to another user immediately they are signed up..
ReplyDeleteNice example, but do you have a mysqli version of the same?
ReplyDeleteCool.
ReplyDeletesupeerrrrbbb great one....
ReplyDeleteThanks Randy :)
Delete