Using Bootstrap 4 to create a modal that is triggered remotely

I am facing an issue with the Modal in remote mode after updating to the latest version of Twitter Bootstrap, which is Bootstrap 4 alpha. While it was working perfectly fine with Bootstrap 3, I now encounter a problem where the popup window appears but the modal body fails to load. It seems like there is no remote call being made to myRemoteURL.do to fetch the content for the modal body.

Here's the code snippet:

<button type="button" data-toggle="modal" data-remote="myRemoteURL.do" data-target="#myModel">Open Model</button>

<!-- Modal -->
<div class="modal fade" id="myModel" tabindex="-1"
    role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                    aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h3 class="modal-title" id="myModalLabel">Model Title</h3>
            </div>
            <div class="modal-body">
                <p>
                    <img alt="loading" src="resources/img/ajax-loader.gif">
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Submit</button>
            </div>
        </div>
    </div>
</div>

Answer №1

Identified the issue: Bootstrap 4 no longer supports the remote option

remote : This option has been deprecated starting from version 3.3.0 and will be completely removed in version 4. It is now recommended to use client-side templating or a data binding framework, or handle it using jQuery.load.

I utilized JQuery to replicate this deprecated functionality.

$('body').on('click', '[data-toggle="modal"]', function(){
        $($(this).data("target")+' .modal-body').load($(this).data("remote"));
    });  

Answer №2

As per the official documentation, it is suggested to follow the instructions provided on this page:

$('#exampleModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var recipient = button.data('whatever') // Extract info from data-* attributes
    // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
    // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
    var modal = $(this)
    modal.find('.modal-title').text('New message to ' + recipient)
    modal.find('.modal-body input').val(recipient)
})

Hence, based on my understanding, the most effective approach (which also works for Bootstrap 5) would be:

<!-- Button trigger modal -->
<a data-bs-toggle="modal" data-bs-target="#modal_frame" href="/otherpage/goes-here">link</a>

<!-- Modal -->
<div class="modal fade" id="modal_frame" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <!-- Complete the modal component definition here -->
</div>

<script>
  $('#modal_frame').on('show.bs.modal', function (e) {
    $(this).find('.modal-body').load(e.relatedTarget.href);
  });
</script>

e.relatedTarget represents the anchor element triggering the modal.

Customize as needed

Answer №3

As mentioned in various answers and the Bootstrap documentation, implementing Bootstrap 4 requires handling the show.bs.modal event to dynamically load content into the modal. This functionality allows for loading content from either an HTML string or a remote URL. Here is an example of how this can be achieved...

$('#theModal').on('show.bs.modal', function (e) {

    var triggerButton = $(e.relatedTarget);
    var targetModal = $(this);

    // Load content from HTML string
    //targetModal.find('.modal-body').html("Custom modal content...");

    // Alternatively, load content from the value of data-remote URL
    targetModal.find('.modal-body').load(triggerButton.data("remote"));

});

See Bootstrap 4 Remote URL Demo here


An alternative approach is to display the modal once data is received from an AJAX request...

$.ajax({
    url: "http://api.example.com/data",
    dataType: 'json',
    success: function(response) {
    
        // Extract data from the AJAX response
        var responseData = response.body;
        // Update modal content with the retrieved data
        $('.modal-body').text(responseData.value);
        // Show the modal
        $('#myModal').modal('show');
    
    },
    error: function(request, status, error) {
        console.log("Something went wrong with the AJAX call: " + request.responseText);
    }
});

Check out the Bootstrap 4 Modal Loading from AJAX Demo

Answer №4

When working with Asp.NET MVC, I found this solution to be effective

HTML

<a href="#" onclick="Edit(1)">Edit item</a>
<div class="modal" id="modalPartialView" />

JQuery

<script type="text/javascript">
        function Edit(id)
        {
            $.ajax({
                url: "@Url.Action("ActionName","ControllerName")",
                type: 'GET',
                cache: false,
                data: {id: id},
            }).done(function(result){
                $('#modalPartialView').html(result)
                $('#modalPartialView').modal('show') //part of bootstrap.min.js
            });
        }
<script>

Action

public PartialViewResult ActionName(int id)
{
   // var model = ...
   return PartialView("_Modal", model);
}

Answer №5

Using the slim version of Jquery (as recommended in Bootstrap 4 documentation and examples) will cause the load function to fail.

To resolve this issue, it is necessary to utilize the full version of Jquery.

Answer №6

This procedure loads the current dynamic data remotely from "remoteContent.html"

<!-- Link to trigger modal -->
<a href="javascript:void(0);" data-remote="remoteContent.html" data-toggle="modal" data-target="#myModal" data-remote="true" class="btn btn-default">
    Launch Modal
</a>
This clever technique: data-remote="remoteContent.html"
<!-- Bootstrap default modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is preventing the JavaScript "onblur" function from being triggered?

I am in the process of developing a website where users can shop using virtual "coins." As part of the testing phase, I have set up a shop where you can see how it works by clicking here. When you click on the "Buy for 40 coins" button, a light blue box s ...

The attachment with Ajax is not displaying any file data

I am encountering an issue while attempting to send an email to myself along with an attachment. Instead of using the standard php mail function, I have opted for PHPMailer due to its convenience. The data is being processed via an Ajax call after extensiv ...

The anchor element does not trigger the activation process within a flexbox item

I have a flex container that contains multiple items. Instead of using the anchor tag to enable a link when clicked, I am setting the flex item class inside it. The element is comprised of three divs: The first div is a circle with an icon, the "second" d ...

What is the correct method for integrating jQuery libraries into an Angular project version 10 or higher?

Currently, I am facing difficulties while attempting to install the jquery and jquery-slimscroll packages into an Angular project (version greater than 10). It appears that the installation of these packages has not been successful. In light of this issue, ...

Tips for resolving issues with the carousel container in bootstrap?

Is there a way to adjust the carousel box container in Bootstrap so that it remains consistent even with images of varying sizes? Currently, the box size changes based on the image dimensions when sliding through the carousel. Sample Code: <h1>Caro ...

Ways to convert a jQuery object into HTML that can be utilized?

When running the code below, an alert message of "object Object" is displayed: var shipImgs = $("#div").children(); alert(shipImgs); The container with id "div" includes a total of 4 children (image tags). <div id="div"> <img src="/imgs/spa ...

Alter the font color upon clicking the menu using jQuery

When I click on the menu and sub-menu items, I want to change their colors along with their parent. You can see an example of how I want it to work here. However, currently, when I click on a sub-menu item, the color of the parent menu item gets removed. ...

I noticed that on my checkout sections, the toggle feature causes them to fold up and then immediately fold back down. This behavior should only happen

Is there a way to make my checkout sections fold up once instead of folding up and down when using toggle? I have created a test case in jsfiddle: (no styling done yet!) http://jsfiddle.net/Wd8Ty/ The code responsible for the behavior is located in AMLRW ...

Utilizing recursive AJAX requests and halting execution at a specified condition

After hours of searching and attempting, I am struggling as a beginner with ajax concepts. Here is my issue: 1. I have a page that retrieves the current date's data from the database, so I am using an ajax function recursively with a setTimeout of 10 ...

I aim to showcase JSON data within a div element

I'm struggling with retrieving JSON data and displaying it on an HTML element. I've tried multiple methods, but none seem to be working. Here is my code: MYAPP.JS $(document).ready(function() { $(function() { switch (menu) { case &apo ...

Using JQuery, Ajax, and PHP for a secure login system

I need a handler for my login process to verify the username and password in the database and redirect the user to another page if the credentials are correct. I am attempting to achieve this using JQuery Ajax and PHP. I have created a JS script to send t ...

The JQuery TextNTags plugin eliminates tag formatting once the trigger syntax has been modified

I have incorporated the JQuery TextNTags plugin into my web application. Here is the original code snippet: $.browser = { webkit: true }; $(function () { $('textarea.tagged_text').textntags({ triggers: {'!': { ...

Tips for keeping Sub Menu visible at all times

Is there a way to keep the sub menu always visible on the homepage of my website's navigation? Thank you for your help! Check out my website here ...

When Flexigrid is loaded using $(document).Ready(), it will not load again if called by another function outside of $(document).Ready()

I have developed a function named "loadTimeTrackersGrid()" that is responsible for loading a flexigrid. Here is how the setup looks: $(document).ready(function () { var editTrackerID = 0; loadTimeTrackersGrid(); )}; The initial section o ...

Tips for displaying or concealing table rows with form fields on a php site by utilizing jquery/ajax and a drop-down menu selection

Is there a way to hide or unhide table rows with form fields in a php website based on a dropdown selection using jquery/ajax? The current script I have only hides the field, leaving blank rows. How can I also hide the respective table rows? Thank you for ...

The functionality of Ajax requests varies across various web browsers

My web app game, Ninja Gold, has been coded using Codeigniter. I have encountered an issue while using Ajax requests to navigate through different routes and retrieve gold amounts from various locations. My ultimate goal was to incorporate continuous back ...

Failing to retain hyperlinks with ajax

Currently, I am utilizing ajax to transmit data from a sophisticated custom field wysiwyg editor. Within this setup, the specific div with the class 'bio' is what I'm addressing. The issue arises when the data is retrieved - all the original ...

Is it possible to resize an inline SVG element without modifying the <svg> tag?

Utilizing a Ruby gem known as rqrcode, I am able to create a QR code in SVG format and send it as an API response. Within my frontend (Vue.js), I am faced with the task of displaying the SVG at a specific size. Currently, my code appears as follows, rende ...

Execute a self-invoking JavaScript function with dynamic code

I'm facing a challenging problem that I just can't seem to solve... There's a function on another website that I need to use, but unfortunately, I can't modify it The code in question is: Now, I am looking to add a prototype "aaa" to ...

Is it possible to detect inline elements that have been wrapped?

I am facing a challenge with displaying an indefinite amount of in-line elements. Depending on the width of the browser, some elements may shift to a new line. I am curious to know if it is possible to identify and isolate these rows of elements, or if the ...