Auto close alert in Twitter Bootstrap with AJAX

Twitter Bootstrap provides alerts in different style to give user some messages regarding his actions and he/she can then close the alert manually later. But there is not functionality to auto close alert in Twitter Bootstrap so here I’m demonstrating how can you auto close alert message with nice fade away & slide effects with using AJAX.

Auto close alert in Twitter Bootstrap

After including all required Bootstrap resources as described in its documentation, we have placed the following markup in our page:

...
<div id="main">
    <!-- Here we will show the alert message -->
    Page data, forms and content
    ...
    <button class="btn btn-default" value="Update" type="submit" name="btn_update" id="btn_update">Update</button>
</div>
...

Now we wish to submit AJAX request to our server side script on click event to the ‘btn_update‘ button while submitting some data to server.

After some processing by user we wish to display an alert message regarding his/her action in this ‘main‘ div which will stay visible for 5 seconds and will fade and let other content below to it slide up smoothly.

Now we will need some jQuery/JavaScript to attend the functionality.

<script type="text/javascript">
    res_success = $('<div class="alert alert-success alert-message" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span class="ajax_response"></span></div>');

    res_fail = $('<div class="alert alert-danger alert-message" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span class="ajax_response"></span></div>');

    function fadeAlert() {
        window.setTimeout(function() {
            $(".alert-message").fadeTo(1500, 0).slideUp(500, function() {
                $(this).remove();
            });
        }, 5000);
    }


    $(document).ready(function() {
        $('#btn_update').click(function() {
            $.ajax({
                url: "update.php", // Specify url to submit
                type: 'post',
                data: data, // Specify post data
                dataType: 'json',
                async: true,
                success: function(json) {
                    if (json.status) {
                        $('.ajax_response', res_success).text(json.message);
                        $('#main').prepend(res_success);
                    } else {
                        $('.ajax_response', res_fail).text(json.message);
                        $('#main').prepend(res_fail);
                    }
                    fadeAlert();
                }
            });
        })
    });
</script>

Here is the explanation of JavaScript code:

  1. We have created two variables containing our alert code, one with ‘success‘ class and another with ‘danger‘ class to mention success/fail status of our request. You can specify only one variable and can insert required class using class functions available in JS/jQuery as well.
  2. A function ‘fadeAlert()‘ is defined to fade the alert and remove after 5 second. A smooth slide up by other content takes place after removal of alert message.
  3. We have used an AJAX request after document ready in button click event and you will need to specify ‘url‘ and ‘data‘ parameters to AJAX request.
  4. We are assuming that our server is replying the request in JSON format containing status, (Boolean true/false) of request processing and a corresponding message.
  5. In success callback, depending on status of our request we are placing server message in respective variable (‘res_success/res_fail‘) and inserting the variable containing the alert markup at top of our ‘main‘ div.
  6. At last as our alert message has been inserted into document, we should call ‘fadeAlert()‘ function to auto close alert message (having class ‘alert-message‘) in Twitter Bootstrap in our this AJAX  example.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.