Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Loading Content in Bootstrap Modal Body via Ajax Using JavaScript</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script> <script> // Define function to load content from remote file function loadContent(url) { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { // Processing the server response if (httpRequest.readyState === XMLHttpRequest.DONE) { if(httpRequest.status === 200) { updateModal(httpRequest.responseText); } else { alert("There was a problem with the request."); } } }; httpRequest.open("GET", url, true); httpRequest.send(); }; // Define function to update modal based on response function updateModal(response) { var myModal = document.getElementById("myModal"); myModal.querySelector(".modal-body").innerHTML = response; } // Load content in modal on activation document.addEventListener("DOMContentLoaded", function() { myModal.addEventListener("show.bs.modal", function() { loadContent("/examples/php/remote.php"); }); }); </script> </head> <body> <div class="m-4"> <!-- Button HTML (to Trigger Modal) --> <button type="button" class="btn btn-lg btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">Launch Demo Modal</button> <!-- Modal HTML --> <div id="myModal" class="modal fade" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Ajax Loading Demo</h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <!-- Content will be loaded here from "remote.php" file --> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">OK, Got it!</button> </div> </div> </div> </div> </div> </body> </html>