简体   繁体   中英

Bootstrap modal - Modal closing immediately on click

I am trying to do a GET request to server and populate the modal with data from database. I am trying to make it like a API so that it is easier for me in the future.

By adding showAjaxModal class to all anchor tags, I am trying to automatically load the modal and do an ajax request to the href attribute of the anchor tag.

However, upon doing so, it all works but the modal immediately disappears and I get this error message:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/ .

JS Fiddle: https://jsfiddle.net/43jj3q30/

Code:

<a class="btn btn-primary showAjaxModal" data-toggle="modal" href="/api/path-to-request" data-target="#modal-id">Trigger modal</a>

Modal:

<div class="modal fade" id="modal-id">

    <div class="modal-dialog">

        <div id="modal-loading-icon"></div>

        <div class="modal-content">

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Modal title</h4>
            </div>

            <div class="modal-body">
                Modal body ...
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>

        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

My Ajax code:

 $('.showAjaxModal').click(function (event) {
            var loadingIcon = $('.modal-loading-icon');
            var ajaxUrl = $(this).attr('href');

            $.ajax({
                url: ajaxUrl,
                beforeSend: function () {
                    loadingIcon.show();
                }
            }).success(function (data) {

                event.preventDefault();
                loadingIcon.hide();
//              $('.modal-body').html(data);
                $('.modal-body').html('test');

            });
        });

What exactly am I doing wrong here? Please help.

Thank you!

change your link to:

<a class="btn btn-primary showAjaxModal">Trigger modal</a>

and add

$('#modal-id').modal('show'); //add this line to your success callback

-

success(function (data) {
   event.preventDefault();
   $('#modal-id').modal('show'); //add
   loadingIcon.hide();
   // $('.modal-body').html(data);
   $('.modal-body').html('test');

   });

working demo: https://jsfiddle.net/43jj3q30/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM