Bootstrap 3 - How to load content in modal body via AJAX?

377,287

Solution 1

Check this SO answer out.

It looks like the only way is to provide the whole modal structure with your ajax response.

As you can check from the bootstrap source code, the load function is binded to the root element.

In case you can't modify the ajax response, a simple workaround could be an explicit call of the $(..).modal(..) plugin on your body element, even though it will probably break the show/hide functions of the root element.

Solution 2

This is actually super simple with just a little bit of added javascript. The link's href is used as the ajax content source. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function.

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Html (based on the official example):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap 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>

Try it yourself: https://jsfiddle.net/ednon5d1/

Solution 3

I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.

The JS part:

$('[data-toggle="ajaxModal"]').on('click',
              function(e) {
                $('#ajaxModal').remove();
                e.preventDefault();
                var $this = $(this)
                  , $remote = $this.data('remote') || $this.attr('href')
                  , $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
                $('body').append($modal);
                $modal.modal({backdrop: 'static', keyboard: false});
                $modal.load($remote);
              }
            );

Finally, in the remote content, you need to put the entire structure to work.

<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
            <a href="#" class="btn btn-primary">Button</a>
            <a href="#" class="btn btn-primary">Another button...</a>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

Solution 4

In the case where you need to update the same modal with content from different Ajax / API calls here's a working solution.

$('.btn-action').click(function(){
    var url = $(this).data("url"); 
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(res) {

            // get the ajax response data
            var data = res.body;

            // update modal content here
            // you may want to format data or 
            // update other modal elements here too
            $('.modal-body').text(data);

            // show modal
            $('#myModal').modal('show');

        },
        error:function(request, status, error) {
            console.log("ajax call went wrong:" + request.responseText);
        }
    });
});

Bootstrap 3 Demo
Bootstrap 4 Demo

Solution 5

A simple way to use modals is with eModal!

Ex from github:

  1. Link to eModal.js <script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
  2. use eModal to display a modal for alert, ajax, prompt or confirm

    // Display an alert modal with default title (Attention)
    eModal.ajax('your/url.html');
    

$(document).ready(function () {/* activate scroll spy menu */

    var iconPrefix = '.glyphicon-';


    $(iconPrefix + 'cloud').click(ajaxDemo);
    $(iconPrefix + 'comment').click(alertDemo);
    $(iconPrefix + 'ok').click(confirmDemo);
    $(iconPrefix + 'pencil').click(promptDemo);
    $(iconPrefix + 'screenshot').click(iframeDemo);
    ///////////////////* Implementation *///////////////////

    // Demos
    function ajaxDemo() {
        var title = 'Ajax modal';
        var params = {
            buttons: [
               { text: 'Close', close: true, style: 'danger' },
               { text: 'New content', close: false, style: 'success', click: ajaxDemo }
            ],
            size: eModal.size.lg,
            title: title,
            url: 'http://maispc.com/app/proxy.php?url=http://loripsum.net/api/' + Math.floor((Math.random() * 7) + 1) + '/short/ul/bq/prude/code/decorete'
        };

        return eModal
            .ajax(params)
            .then(function () { alert('Ajax Request complete!!!!', title) });
    }

    function alertDemo() {
        var title = 'Alert modal';
        return eModal
            .alert('You welcome! Want clean code ?', title)
            .then(function () { alert('Alert modal is visible.', title); });
    }

    function confirmDemo() {
        var title = 'Confirm modal callback feedback';
        return eModal
            .confirm('It is simple enough?', 'Confirm modal')
            .then(function (/* DOM */) { alert('Thank you for your OK pressed!', title); })
            .fail(function (/*null*/) { alert('Thank you for your Cancel pressed!', title) });
    }

    function iframeDemo() {
        var title = 'Insiders';
        return eModal
            .iframe('https://www.youtube.com/embed/VTkvN51OPfI', title)
            .then(function () { alert('iFrame loaded!!!!', title) });
    }

    function promptDemo() {
        var title = 'Prompt modal callback feedback';
        return eModal
            .prompt({ size: eModal.size.sm, message: 'What\'s your name?', title: title })
            .then(function (input) { alert({ message: 'Hi ' + input + '!', title: title, imgURI: 'https://avatars0.githubusercontent.com/u/4276775?v=3&s=89' }) })
            .fail(function (/**/) { alert('Why don\'t you tell me your name?', title); });
    }

    //#endregion
});
.fa{
  cursor:pointer;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet" >
<link href="http//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">

<div class="row" itemprop="about">
	<div class="col-sm-1 text-center"></div>
	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10 text-center">
				<h3>Ajax</h3>
				<p>You must get the message from a remote server? No problem!</p>
				<i class="glyphicon glyphicon-cloud fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>
	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10 text-center">
				<h3>Alert</h3>
				<p>Traditional alert box. Using only text or a lot of magic!?</p>
				<i class="glyphicon glyphicon-comment fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>

	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10 text-center">
				<h3>Confirm</h3>
				<p>Get an okay from user, has never been so simple and clean!</p>
				<i class="glyphicon glyphicon-ok fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>
	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10  text-center">
				<h3>Prompt</h3>
				<p>Do you have a question for the user? We take care of it...</p>
				<i class="glyphicon glyphicon-pencil fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>
	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10  text-center">
				<h3>iFrame</h3>
				<p>IFrames are hard to deal with it? We don't think so!</p>
				<i class="glyphicon glyphicon-screenshot fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>
	<div class="col-sm-1 text-center"></div>
</div>
Share:
377,287

Related videos on Youtube

Thiezar
Author by

Thiezar

Updated on January 26, 2021

Comments

  • Thiezar
    Thiezar over 3 years

    As you can see here, I have a button that launches a modal. Setting an href url for the button this url is automatically loaded into modal by Bootstrap 3. The fact is this page is loaded into modal root (as said in the bootstrap 3 documentation for modals usage). I want to load it into the modal-body instead.

    Is there a way to do it via attributes (not javascript)? Or what is the most automatic way to do it?

    P.S. I remember in Bootstrap 2 the content was loaded in the body, not the root.

  • JasonDavis
    JasonDavis almost 9 years
    In the newest Bootrat, the load function has be depracated and says this in the Boostrap docs: This option is deprecated since v3.3.0 and will be removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself. would love to see an updated version for this
  • marcovtwout
    marcovtwout almost 9 years
    Did you comment on the wrong answer? This answer does exactly that. ;)
  • Laurence
    Laurence almost 9 years
    This triggers 2x ajax calls in Bootstrap v3. One for the original Modal AJAX load - and one for your show.bs.modal event (which is fired after the original ajax call).
  • marcovtwout
    marcovtwout almost 9 years
    Thanks for noticing this. The official docs weren't very clear here - I now specifically disabled the original load through data-remote="false" and added a JSfiddle. In Bootstrap 4 this should no longer be needed.
  • Mike Castro Demaria
    Mike Castro Demaria over 8 years
    Look nice to use it, but a full real example of code ( maybe usine jsfiddle.net ) will be more interesting.
  • Samuel Pinto
    Samuel Pinto over 8 years
    Hi Mike, take a look in post edition... I Added a full demo from official site
  • Someone Special
    Someone Special about 8 years
    This is exactly the way i'm doing now except i have a modal_create_head and modal_create_foot function and then i throw whatever ajax return in between. I thought this would be faster than loading a html in the ajax box since your .js file will be cache by the client side and keep reusing it, no? Why people load .html instead of returning all the html codes in Json or Text or HTML, is loading HTML faster?
  • Hokascha
    Hokascha over 7 years
    Is there a simple way to set the modal title, too? First thought was to make a second ajax call but that's not nice...
  • marcovtwout
    marcovtwout over 7 years
    @Hokascha that depends on where you want to set the title from. You could set it through a modal event handler like this: $(this).find('.modal-title').text('New title). See: getbootstrap.com/javascript/#modals-related-target
  • Paul Bormans
    Paul Bormans about 7 years
    Notice you can use the complete callback to bind to controls that you load.
  • nj2237
    nj2237 about 6 years
    please do not use code format for explanation of code - separate them
  • neophyte
    neophyte almost 6 years
    Nice, clean and effective! Recommended as well.