The modal window can be shown using jQuery, Bootstrap, and others. This tutorial will show the Bootstrap modal with dynamically loaded content.
The content is stored in a Database table which is retrieved and loaded dynamically into the modal body. In a previous tutorial, we have seen how to show a modal window by using the core jQuery library without Bootstrap.
In this example, I have shown three buttons that trigger the jQuery AJAX load() method. I have specified the PHP file name used to request the dynamic content from the database, also a callback to enable modal visibility.
In a previous tutorial, we have seen how to load page content from the database using PHP and AJAX.
This HTML code shows the buttons handling events for getting dynamic content for the Bootstrap model window. It also contains the modal window container with the modal header, footer, and body elements.
The header and the footer show the static content for displaying the title and a close button, respectively. The modal body is left empty and will be loaded dynamically by clicking the buttons.
<div id="demo-modal-target">
<div class="demo-title">Bootstrap Dynamic Modal Window</div>
<div onclick="loadDynamicContentModal('bootstrap')"
class="btn-modal-target" id="btn-bootstrap">Bootstrap</div>
<div onclick="loadDynamicContentModal('jquery')"
class="btn-modal-target" id="btn-jquery">jQuery</div>
<div onclick="loadDynamicContentModal('responsive')"
class="btn-modal-target" id="btn-responsive">Responsive</div>
</div>
<div class="modal fade" id="bootstrap-modal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Bootstrap Dynamic Modal
Content</h4>
</div>
<div id="demo-modal"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The following jQuery function will be called on the button click event. In this event, the content category is sent to the PHP code to get the content data from the database based on the category selected.
PHP code sends the response HTML to be loaded dynamically onto the modal window.
<script>
function loadDynamicContentModal(modal) {
var options = {
modal : true,
height : 300,
width : 500
};
$('#demo-modal').load('get-dynamic-data.php?modal=' + modal,
function() {
$('#bootstrap-modal').modal({
show : true
});
});
}
</script>
And the PHP code is,
<?php
require ("DBController.php");
$dbController = new DBController();
$query = "SELECT * FROM tbl_modal_content WHERE modal = '" . $_GET["modal"] . "'";
$result = $dbController->runQuery($query);
if(!empty($result))
{
?>
<img src='<?php echo $result[0]["image"]?>' />
<div class='modal-text'>
<?php echo $result[0]["modal_content"]?>
</div>
<?php
}
?>