You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap Modal数据库增改正常,但Alert提示不生效求助

Fixing Bootstrap Alert Not Working in Modal with PHP/Ajax

Hey there! Since your database insert/update operations are working fine, the issue with your Bootstrap Alert not showing up is almost certainly related to how the alert is being injected into the modal or the display logic in your JavaScript. Let's walk through the fixes step by step:

1. Fix the Alert Display Logic

Your current code uses .show(10) and .hide(10) which might not play well with Bootstrap's alert component. Instead, use Bootstrap's built-in fade classes and native alert methods to ensure the alert appears correctly in the modal context.

2. Correct Font Awesome Icon Typo

In your error handling branch, you're using <i class=\"fa fa-cross\"></i> — Font Awesome doesn't have a fa-cross icon. Replace it with fa-times to avoid broken icon rendering (this doesn't fix the alert, but it's a quick cleanup).

3. Ensure JSON Response is Properly Formatted

Double-check your PHP backend (shouts.php) to make sure it's returning valid JSON with the correct headers. Add this at the top of your PHP script before any output:

header('Content-Type: application/json');

And make sure your response array is structured correctly, like:

echo json_encode([
    'success' => true,
    'messages' => 'Shout added successfully!'
]);
exit;

Modified JavaScript Code

Here's the adjusted JavaScript with fixes for the alert display and icon typo:

<script>
$(document).ready(function(){
    $("#shoutOutForm").unbind('submit').bind('submit', function() {
        $('.form-group').removeClass('has-error').removeClass('has-success');
        $('.text-danger').remove();

        var sigaw = $("#sigaw").val();
        var username = $("#username").val();

        if(sigaw == "") {
            $("#sigaw").after('<p class="text-danger">Shout Out field is required</p>');
            $('#sigaw').closest('.form-group').addClass('has-error');
        } else {
            $("#sigaw").find('.text-danger').remove();
            $("#sigaw").closest('.form-group').addClass('has-success');
        }

        if(sigaw) {
            var form = $(this);
            $("#shoutOutBtn").button('loading');

            $.ajax({
                url : form.attr('action'),
                type: form.attr('method'),
                data: form.serialize(),
                dataType: 'json',
                beforeSend: function() {
                    $('#shoutOutBtn').html("<div class='spinner-border text-light' role='status'></div> Shouting ...");
                    $("#shoutOutBtn").prop('disabled', true);
                },
                success:function(response) {
                    $("#shoutOutBtn").button('reset');

                    if(response.success == true) {
                        $("#shoutOutForm")[0].reset();
                        $(".text-danger").remove();
                        $('.form-group').removeClass('has-error').removeClass('has-success');
                        
                        // Insert alert with Bootstrap's fade animation
                        var successAlert = '<div class="alert alert-success alert-dismissible fade show" role="alert">'+
                                            '<strong><i class="fa fa-check"></i></strong> '+ response.messages +
                                            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'+
                                            '<span aria-hidden="true">&times;</span>'+
                                            '</button></div>';
                        
                        $('#buttonAlert').html(successAlert);
                        
                        // Auto-hide after 3 seconds
                        setTimeout(function() {
                            $('.alert-success').alert('close');
                            $("#shoutOutBtn").prop('disabled', false);
                            $('#shoutOutBtn').html("<i class=\"fa fa-check\"></i> Shout");
                        }, 3000);
                    } else {
                        $("#shoutOutForm")[0].reset();
                        $(".text-danger").remove();
                        $('.form-group').removeClass('has-error').removeClass('has-success');
                        
                        // Insert error alert with fade animation
                        var errorAlert = '<div class="alert alert-danger alert-dismissible fade show" role="alert">'+
                                          '<strong><i class="fa fa-exclamation-triangle"></i></strong> '+ response.messages +
                                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'+
                                          '<span aria-hidden="true">&times;</span>'+
                                          '</button></div>';
                        
                        $('#buttonAlert').html(errorAlert);
                        
                        setTimeout(function() {
                            $('.alert-danger').alert('close');
                            $("#shoutOutBtn").prop('disabled', false);
                            $('#shoutOutBtn').html("<i class=\"fa fa-times\"></i> Shout");
                        }, 3000);
                    }
                }
            });
        }
        return false;
    });
});
</script>

Key Changes Made:

  • Used Bootstrap's alert-dismissible fade show classes to ensure proper animation and dismissal functionality
  • Replaced custom show/hide logic with Bootstrap's native .alert('close') method
  • Fixed the Font Awesome icon from fa-cross to fa-times
  • Simplified alert insertion code for better readability
  • Used setTimeout instead of .delay() for more reliable timing

Original Code for Reference

HTML (Modal & Form)

<div class="responsive">
  <div class="modal fade" id="myModal2" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Shout Box!</h4>
        </div>
        <div class="modal-body">
          <!-- Form -->
          <form class="text-center" style="color: #757575;" id="shoutOutForm" name="shoutOutForm" action="shouts.php" method="POST">
            <!-- Form Start -->
            <section class="forms">
              <div class="container-fluid">
                <!-- Page Header-->
                <div id="buttonAlert"></div>
                <div class="row">
                  <div class="col-lg-6">
                    <div class="card-body">
                      <?php $user_id = $wo["user"]["id"]; ?>
                      <input type="text" id="sigaw" name="sigaw" value="">
                      <input type="hidden" id="username" name="username" value="<?= $user_id ?>">
                    </div>
                  </div>
                </div>
              </div>
            </section>
        </div><!-- End Modal Body -->
        <!-- Form End -->
        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="submit" class="btn btn btn-success" id="shoutOutBtn" data-loading-text="Shouting...">
            <i class="fa fa-check"></i> Shout</button>
          <button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-power-off"></i> Close</button>
        </div>
        <!-- possible cause of undesired error, not OP comment! -->
        </form>
      </div>
    </div>
  </div>
</div>

Original JavaScript

<script>
$(document).ready(function(){
    // submit customers form function
    $("#shoutOutForm").unbind('submit').bind('submit', function() {
        $('.form-group').removeClass('has-error').removeClass('has-success');
        $('.text-danger').remove();

        var sigaw = $("#sigaw").val();
        var username = $("#username").val();

        if(sigaw == "") {
            $("#sigaw").after('<p class="text-danger">Shout Out field is required</p>');
            $('#sigaw').closest('.form-group').addClass('has-error');
        } else {
            // remov error text field
            $("#sigaw").find('.text-danger').remove();
            // success out for form
            $("#sigaw").closest('.form-group').addClass('has-success');
        }

        if(sigaw) {
            var form = $(this);
            // button loading
            $("#shoutOutBtn").button('loading');

            $.ajax({
                url : form.attr('action'),
                type: form.attr('method'),
                data: form.serialize(),
                dataType: 'json',
                beforeSend: function() {
                    $('#shoutOutBtn').html("<div class='spinner-border text-light' role='status'></div> Shouting ...");
                    $("#shoutOutBtn").prop('disabled', true); // disable button
                },
                success:function(response) {
                    // button loading
                    $("#shoutOutBtn").button('reset');

                    if(response.success == true) {
                        // reload the manage member table
                        // reset the form text
                        $("#shoutOutForm")[0].reset();
                        // remove the error text
                        $(".text-danger").remove();
                        // remove the form error
                        $('.form-group').removeClass('has-error').removeClass('has-success');

                        $('#buttonAlert').html('<div class="alert alert-success">'+
                            '<button type="button" class="close" data-dismiss="alert">&times;</button>'+
                            '<strong><i class="fa fa-check"></i></strong> '+ response.messages +
                            '</div>');

                        $(".alert-success").delay(500).show(10, function() {
                            $(this).delay(3000).hide(10, function() {
                                $(this).remove();
                                $("#shoutOutBtn").prop('disabled', false); // disable button
                                $('#shoutOutBtn').html("<i class=\"fa fa-check\"></i> Save");
                            });
                        }); // /.alert

                    } else {

                        $("#shoutOutForm")[0].reset();
                        // remove the error text
                        $(".text-danger").remove();
                        // remove the form error
                        $('.form-group').removeClass('has-error').removeClass('has-success');

                        $('#buttonAlert').html('<div class="alert alert-danger">'+
                            '<button type="button" class="close" data-dismiss="alert">&times;</button>'+
                            '<strong><i class="fa fa-check"></i></strong> '+ response.messages +
                            '</div>');

                        $(".alert-danger").delay(500).show(10, function() {
                            $(this).delay(3000).hide(10, function() {
                                $(this).remove();
                                $("#shoutOutBtn").prop('disabled', false); // disable button
                                $('#shoutOutBtn').html("<i class=\"fa fa-cross\"></i> Save");
                            });
                        }); // /.alert
                    }
                } // /success
            }); // /ajax
        } // if
        return false;
    }); // submit customers form function
});
</script>

内容的提问来源于stack exchange,提问作者Chek Beltran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:45:52