medk
medk

Reputation: 9549

Making Bootstrap 5 Modal Load Content with AJAX

As Bootstrap doesn't offer AJAX content for the Modal, I wanted to find a workaround, but without success:

Here is the modal to be fired with just "Loading..."

<div class="modal fade" id="edit-pp" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="editppLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="m-3">Loading...</div>
        </div>
    </div>
</div>

Here is the content to be added with AJAX:

<div class="modal-header">
    <h5 class="modal-title" id="changeppLabel">Header Title</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
    --- Modal body content here ---
</div>
<div class="modal-footer" style="justify-content: space-between;">
    --- Modal body content here ---
</div>

Here is the link to open the modal, with a jQuery function attached to make the AJAX call:

<a class="" href="#" id="edit-pp-modal" data-bs-toggle="modal" data-bs-target="#edit-pp" onclick="showEditPP()">Open Modal</a>

Here is the jQuery code:

function showEditPP() {
    $.get('core/profile-photo-edit.php', function(data) {
        $('.modal-body').html(data);
    });
}

Now, this code runs and gets the AJAX response from the server, but the opend modal itself doesn't get updated, instead, keeps showing "Loading..."

I found an example with another aproach but it's not what I need, as in the example I found, nothing happens until the data is fully loaded and appended to the modal, then the modal is shown. So, no loading or anything is telling the user to wait.

Now what's the best approach here to follow, so when the user clicks:

  1. The modal opens with "Loading..."
  2. Content is loaded with AJAX and appended the the modal
  3. the modal itself is reset (content removed) after closing the modal

Thanks

Upvotes: 1

Views: 5068

Answers (1)

ruleboy21
ruleboy21

Reputation: 6371

You're using the wrong selector. Change

$('.modal-body').html(data);

To this instead

$('#edit-pp .modal-content').html(data);

Upvotes: 1

Related Questions