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:

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.

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.
Like this Post? Share