Dynamic Bootstrap 5 Modal Windows via AJAX – loadmodal.js

Category: Modal & Popup | November 23, 2025
Authorwebdotpulse
Last UpdateNovember 23, 2025
LicenseMIT
Views53 views
Dynamic Bootstrap 5 Modal Windows via AJAX – loadmodal.js

loadmodal.js is a vanilla JavaScript plugin for Bootstrap that loads modal content via Ajax using the Fetch API.

Standard Bootstrap modals force you to write empty HTML markup in your DOM before you can use them.

This library solves that by fetching your content first, generating the necessary HTML on the fly, and injecting it into the page.

It keeps your initial markup clean and loads resources only when the user requests them.

Features:

  • Fetch API: Uses native fetch() to retrieve remote content.
  • Dynamic DOM: Builds the modal header, body, and footer automatically.
  • Promise-Based API: Supports method chaining (.create(), .show(), .close()) and standard .then() handling.
  • Custom Button Logic: Allows definition of button labels and callbacks directly in JavaScript.
  • Automatic Cleanup: Removes the modal from the DOM immediately after it closes.
  • Smart Focus Management: Automatically focuses the first input field inside the loaded content.

Use Cases:

  • Admin Dashboards: Load edit forms, user details, or confirmation dialogs from server endpoints without page refreshes.
  • E-commerce Applications: Display product details, shipping information, or checkout forms in modals fetched from backend APIs.
  • Content Management Systems: Open content previews, media galleries, or inline editing interfaces loaded dynamically based on user actions.
  • Data Tables: Show detailed record information or action confirmations when users click table rows without navigating away from the list view.

How To Use It:

1. Include Bootstrap 5 and the loadmodal.js library in your HTML document.

<!-- Bootstrap is required -->
<link rel="stylesheet" href="/path/to/cdn/bootstrap.min.css" />
<script src="/path/to/cdn/bootstrap.bundle.min.js"></script>
<!-- loadmodal.js -->
<script src="/path/to/loadmodal.js"></script>

2. The simplest implementation requires only a URL string. The plugin fetches content and displays it in a modal with default settings.

This creates a modal with the document title, standard width, and a close button. The server endpoint should return HTML content to populate the modal body.

// Simple modal with default configuration
loadmodal('/path/to/api');

3. You can pass a configuration object to control the modal’s size, buttons, and events.

  • url (string, required): Server endpoint URL to fetch modal content.
  • id (string, default: 'loadmodal-js'): Unique ID assigned to the modal element.
  • title (string, default: document title): Text displayed in modal header.
  • width (string, default: '400px'): CSS width value applied to modal dialog.
  • size (string, default: 'modal-lg'): Bootstrap size class (modal-sm, modal-lg, modal-xl).
  • closeButton (boolean, default: true): Show or hide the X close button in header.
  • buttons (object, default: {}): Object mapping button labels to callback functions. Return false from callback to prevent modal closing.
  • modal (object): Options passed directly to Bootstrap’s new bootstrap.Modal() constructor (backdrop, keyboard, focus).
  • fetch (object): Options passed to the Fetch API (method, headers, body, credentials).
  • onCreate (function|array): Callback(s) executed after modal HTML is created but before display. Receives fetched data as parameter.
  • onShow (function|array): Callback(s) executed when modal becomes visible. Receives Bootstrap shown.bs.modal event.
  • onClose (function|array): Callback(s) executed when modal is hidden. Receives Bootstrap hidden.bs.modal event.
  • onSuccess (function|array): Callback(s) executed after successful fetch but before modal creation. Receives response text and can modify it by returning a string.
loadmodal({
  url: '/path/to/api/',
  id: 'user-modal',
  title: 'Edit User Profile', 
  width: '600px', 
  size: 'modal-lg', 
  // Define custom buttons in the footer
  buttons: {
    "Save Changes": function(event) {
      // Logic to save data goes here
      console.log('Save clicked');
      // Return false to prevent the modal from closing automatically
      return true; 
    },
    "Cancel": false, // A value of false creates a standard close button
  },
  // Standard Fetch API options
  fetch: {
    method: 'GET',
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  }
})
.create(function(data) {
  // Runs after HTML is generated but before the modal appears
  console.log('DOM element created');
})
.show(function(event) {
  // Runs when the modal is fully visible to the user
  console.log('Modal is visible');
})
.close(function(event) {
  // Runs when the modal is hidden and about to be removed
  console.log('Modal closed');
});

Tip: Use onSuccess callbacks to sanitize or transform server responses before they render in the modal body.

Alternatives:

  • bootstrap-show-modal: Offers similar functionality but includes built-in loading indicators and error handling at the cost of a larger file size.
  • Micromodal.js:  A lightweight JavaScript library for inserting animated, accessible modal windows into your document.
  • Bootbox.js: A classic library for Bootstrap modals. It is more feature-rich but historically relied on jQuery.

FAQs

Q: Does the plugin work with Bootstrap 4?
A: No, loadmodal.js targets Bootstrap 5 specifically. The API differences between Bootstrap 4 and 5 modal implementations make them incompatible. Use version 1.x of loadmodal for Bootstrap 4 support if available.

Q: How do I display a loading spinner while content fetches?
A: The plugin does not include built-in loading states. Implement your own by showing a spinner before calling loadmodal and hiding it in the onCreate callback. Alternatively, return a loading HTML template from your server initially and update it via JavaScript once the full content has loaded.

Q: Can I modify the fetched content before it displays in the modal?
A: Yes, use the onSuccess callback option. This function receives the response text and can transform it by returning a modified string. Multiple onSuccess callbacks execute in sequence, allowing content pipeline processing.

Q: What happens if I call loadmodal with an ID that already exists?
A: The plugin automatically closes and removes any existing modal with the same ID before creating the new one. This prevents duplicate modals and ensures clean state management.

Q: How do I prevent the modal from closing when a button is clicked?
A: Return false from your button callback function. The plugin checks the return value and only closes the modal if the callback returns a truthy value or nothing. This pattern works well for form validation scenarios where you need to keep the modal open on errors.

Q: How do I close the modal programmatically?
A: You can use standard Bootstrap logic. Get the element by ID and call .hide() on the instance, or return true from a button callback.

You Might Be Interested In:


Leave a Reply