This is the easiest way to create dynamic bootstrap modal with jquery on your web page. The Modal plugin is a dialogue box or a popup window that is displayed on top of your current page.
On the other hand, we can say modal is a child window of the parent window. The purpose is to display data from a separate source that can have some interaction without leaving the parent page.
One more very important thing is the user can add/update/insert records in the database with the help of Modal and jquery Ajax.
Download Now Laravel Project with Admin Dashboard
Jquery ajax modal popup example
You can show Bootstrap Modal by clicking on the button or link via data attributes without writing any script, but we are going to introduce how to create Modal with dynamic value and dynamic form where you can update your record.
Bootstrap Modal code is:
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal Title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
//modal body data
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Bootstrap modal load content ajax
Now we are going to write code to generate a list of records using JQuery Ajax and bind a modal for this list.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Modal</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2 class="text-danger">Bootstrap Modal with update usnig Ajax</h2>
<table id="result" class="table table-striped"></table>
<div id="loader-icon"><i class="fa fa-refresh fa-spin" style="font-size:20px"></i></div>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Information</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="form-horizontal modal-form" role="form"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
$('#myModal').on('shown.bs.modal', function (e) {
var heading = [];
var data = [];
var id = $(e.relatedTarget).data('id');
heading = $('.text-info').find('th').map(function(){
return this.innerHTML;
}).get();
data = $('#row'+id).find('td').map(function(){
return this.innerHTML;
}).get();
$('.modal-form').html(null);
$.each( heading, function( key, value ) {
$('.modal-form').append('<div class="form-group"><label class="col-sm-2 control-label">'+value+'</label><div class="col-sm-10"><input type="text" class="form-control" name="'+value.toLowerCase()+'" value="'+data[key]+'" placeholder="Fill this field"/></div></div>');
});
$("#myModal .btn-primary" ).click(function() {
$.ajax({
url: 'ajax_page.php',
type: "POST",
data: $(".modal-form").serialize() + "&action=save_modal_data",
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
alert(data)
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
console.debug("Internal error: " + jqXHR.responseText)
} else {
console.debug("Unexpected error.")
}
}
});
});
})
function getresult(offset,limit) {
$.ajax({
url: 'ajax_page.php',
type: "POST",
data: {action:'show_list',offset:offset,limit:limit},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#result").append(data);
window.busy = false;
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
console.debug("Internal error: " + jqXHR.responseText)
} else {
console.debug("Unexpected error.")
}
}
});
}
var busy = false;
var offset = 0;
var limit = 15;
$(window).scroll(function(){
if($(window).scrollTop()==$(document).height()-$(window).height()){
busy = true;
offset = offset + limit;
getresult(offset, limit)
}
});
getresult(offset, limit);
</script>
Bootstrap Modal with an update using Ajax
Database connection cofig.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$connection) {
die("Connection failed: " . $connection->connect_error);
}
function close_db(){
mysqli_close($connection);
}
?>
Ajax page for update record onClick of the model button and fetch record from database:
<?php
require_once('../config.php');
if(isset($_POST['action'])){
$action = $_POST['action'];
if($action == 'show_list'){
$offset = $_POST['offset'];
$limit = $_POST['limit'];
$mysql_query = mysqli_query($connection, "Select * from country Limit $offset, $limit");
if($offset == 0){
echo "<thead>
<tr class='text-info'>";
while($mysql_query_fields = mysqli_fetch_field($mysql_query)){
$mysql_fields[] = $mysql_query_fields->name;
echo "<th align='left'>".ucfirst($mysql_query_fields->name)."</th>";
}
echo "</tr>
</thead>";
}
else{
while($mysql_query_fields = mysqli_fetch_field($mysql_query)){
$mysql_fields[] = $mysql_query_fields->name;
}
}
while($mysql_rows = mysqli_fetch_array($mysql_query)){
echo "<tr id='row".$mysql_rows['id']."'>";
foreach($mysql_fields as $fields){
echo "<td>".$mysql_rows[$fields]."</td>";
}
echo "<td><button type='button' class='btn btn-info btn-lg' data-toggle='modal' data-id='".$mysql_rows['id']."' data-target='#myModal'><span class='glyphicon glyphicon-cog'></span></button></td>";
echo "</tr>";
}
}
if($action == 'save_modal_data'){
$sql = "UPDATE country SET nicename = '".$_POST['nicename']."' WHERE id = ".$_POST['id'];
if(mysqli_query($connection, $sql)){
echo "Records updated successfully.";
} else{
echo "ERROR: Could not able to execute. $sql" . mysqli_error($connection);
}
}
else{
echo "Invalid Method!";
}
}
else{
echo "Invalid Calling Method!";
}
close_db($connection);
?>
Write a comment