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

Thiezar picture Thiezar · Oct 29, 2013 · Viewed 347.7k times · Source

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.

Answer

marcovtwout picture marcovtwout · Dec 31, 2014

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/