Home > other >  Making Bootstrap 5 Modal Load Content with AJAX
Making Bootstrap 5 Modal Load Content with AJAX

Time:12-08

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  id="edit-pp" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="editppLabel" aria-hidden="true">
    <div >
        <div >
            <div >Loading...</div>
        </div>
    </div>
</div>

Here is the content to be added with AJAX:

<div >
    <h5  id="changeppLabel">Header Title</h5>
    <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div >
    --- Modal body content here ---
</div>
<div  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  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

CodePudding user response:

You're using the wrong selector. Change

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

To this instead

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