Ajax Loaded Bootstrap Modal with PHP & MySQL

In this tutorial, you will learn how to create dynamic Boostrap Modal with Ajax, PHP and MySQL. As we know that Modals are important part of any website that enables to perform different actions like add, update, delete and even display dynamic content. In this tutorial, we have cover up functionality to display Modal loaded with dynamic content using Ajax, PHP and MYSQL.

Also, read:

You can check the live demo and also download running demo script to try yourself.

So let’s start the coding.

Steps1: Create MySQL Database Table
For this tutorial, we have used MySQL database table “employee” to display employee records and then load details in modal. So we will use below code to create table.


CREATE TABLE IF NOT EXISTS `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key',
  `employee_name` varchar(255) NOT NULL COMMENT 'employee name',
  `employee_salary` double NOT NULL COMMENT 'employee salary',
  `employee_age` int(11) NOT NULL COMMENT 'employee age',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=11 ;

Now we will import employee data using below queries

INSERT INTO `employee` (`id`, `employee_name`, `employee_salary`, `employee_age`) VALUES
(1, 'Tiger Nixon', 3208000, 61),
(2, 'Garrett Winters', 170750, 63),
(3, 'Ashton Cox', 86000, 66),
(4, 'Cedric Kelly', 433060, 22),
(5, 'Airi Satou', 162700, 33),
(6, 'Brielle Williamsons', 372000, 61),
(7, 'Herrod Chandler', 137500, 59),
(8, 'Rhona Davidson', 327900, 55),
(9, 'Colleen Hurst', 205500, 39),
(10, 'Sonya Frost', 103600, 23);

Steps2: Create MySQL Database Connection
We will create db_connect.php PHP file to make connection with MySQL database.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phpzag_demos";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
?>

Steps3: Include Bootstrap, jQuery and JavaScript Files
In this tutorial, We have created PHP file index.php and included all necessary library files (Bootstrap, jQuery) and CSS files in head tag. In this tutorial, we have created HTML using Bootstrap. The JavaScript file ajaxData.js handle employee data load on click event and make Ajax request to load data.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript" src="script/ajaxData.js"></script>

Steps4: List Employee Records
Now in index.php, we will display employee records from MySQL database table and create View button to display modal on click with employee details loaded through Ajax.

<table class="table table-striped table-bordered">              
<thead>
<tr>
<th>Employee Name</th>
<th>Detail</th>
</tr>
</thead>              
<tbody>           
<?php
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee LIMIT 5";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) { 
?>
<tr>
<td><?php echo $rows["employee_name"]; ?></td>
<td>
<button data-toggle="modal" data-target="#emp-modal" data-id="<?php echo $rows["id"]; ?>" id="getEmployee" class="btn btn-sm btn-info">
<i class="glyphicon glyphicon-eye-open"></i> View</button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>

Steps5: Load Employee Data with jQuery Ajax
Now in ajaxData.js JavaScript file, we will handle to get clicked employee id and make Ajax request to server empData.php to get clicked employee details from MySQL database table employee. The Ajax request gets response employee data in JSON format from server. We will display that response JSON data with jQuery in Modal.


$(document).ready(function(){ 	
	 $(document).on('click', '#getEmployee', function(e){  
     e.preventDefault();  
     var empid = $(this).data('id');    
	  $('#employee-detail').hide();
     $('#employee_data-loader').show();  
     $.ajax({
          url: 'empData.php',
          type: 'POST',
          data: 'empid='+empid,
          dataType: 'json',
		  cache: false
     })
     .done(function(data){
          console.log(data.employee_name); 
          $('#employee-detail').hide();
		  $('#employee-detail').show();
		  $('#empid').html(data.id);
		  $('#emp_name').html(data.employee_name);
		  $('#emp_age').html(data.employee_age);
		  $('#emp_salary').html("$"+data.employee_salary);		 
		  $('#employee_data-loader').hide();
     })
     .fail(function(){
          $('#employee-detail').html('Error, Please try again...');
          $('#employee_data-loader').hide();
     });
    });	
});

Steps6: Get Employee Data from MySQL Database
Now finally in empData.php, we will get employee details from MySQL database table and return data as JSON using json_encode.

<?php
include_once("db_connect.php");
if($_REQUEST['empid']) {
	$sql = "SELECT id, employee_name, employee_salary, employee_age
 FROM employee WHERE id='".$_REQUEST['empid']."'";
	$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));	
	$data = array();
	while( $rows = mysqli_fetch_assoc($resultset) ) {
		$data = $rows;
	}
	echo json_encode($data);
} 
?>

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download