Search code examples
jquerybootstrap-4popover

Dynamically change content of a Bootstrap 4 popover using Ajax


I want to set the content of a Bootstrap4 popover with html from an ajax call.

There are plenty of solutions for Bootstrap 3 but am having trouble finding a solution for Bootstrap version 4.

Here is my HTML:

                <button type="button"
                        id="AlertsBellButton"
                        class="btn btn-lg btn-danger"
                        data-toggle="popover"
                        data-placement="bottom"
                        data-trigger="focus" 
                        title="Alerts"
                        data-html="true"
                        data-content="Loading...">
                    <i class="fal fa-bell"></i>
                </button>

And my Javascript:

$('#AlertsBellButton').on('show.bs.popover', function () {
    $.ajax({
        url: '/Alert/GetAlertsForBell/',
        type: 'get',
        cache: false,
        success: function (data) {

            $('#AlertsBellButton').attr('data-content', data);
        }
    });
});

Setting the data-content attribute apparently should do the trick however; the first time I click the bell, the content shows "Loading..." even after the first ajax call completes and when I click the second time, the correct data shows.

I've also tried targeting the div using jQuery in the success handler, but this didn't work as the popover isn't added to the DOM yet by Bootstrap4.


Solution

  • For anyone else who gets stuck, I added some custom html as the content with an id:

                    <button type="button"
                            id="AlertsBellButton"
                            class="btn btn-lg btn-danger"
                            data-toggle="popover"
                            data-placement="right"
                            data-trigger="focus"
                            title="Alerts"
                            data-html="true"
                            data-content="<div id='AlertBellContainer'>Loading...</div>">
                        <span class="sr-only">Notifications</span>
                        <i class="fal fa-bell"></i>
                    </button>
    

    And then simply set the html of my in the success handler by targeting the custom html:

    $('#AlertsBellButton').on('show.bs.popover', function (e) {
        $.ajax({
            url: '/Alert/GetAlertsForBell/',
            type: 'get',
            cache: false,
            success: function (data) {
                $('#AlertBellContainer').html(data);                            
            }
        });
    });