Tuesday, April 28, 2015

Use bootstrap to display success or error messages

After "Submit" button is clicked, it is very common to display success or error message in the same page instead of refreshing the whole page. (See pictures below.)



After click "Save Classes" button, I have an ajax to post the form data to server side. If it success, a success message will be displayed at the bottom of the form. If ajax call failed, an error message will be displayed. I use BootStrap to display alter messages.

The javascript code for the ajax is as following:

      // Use Ajax to submit form data  
      $.ajax({  
                     url : $form.attr('action'),  
                     type : 'POST',  
                     data : $form.serializeObject(),  
                     success : function(result) {  
                          // ... Process the result ...  
                           $("#result").html('<a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> Your message has been sent successfully.');   
                       $("#result").addClass("alert alert-success");  
                     },  
                     error : function(xhr,textStatus,errorThrown) {                           
                           $("#result").html('<a href="#" class="close" data-dismiss="alert">&times;</a><strong>Error!</strong> A problem has been occurred while saving your classes.');   
               $("#result").addClass("alert alert-danger alert-error");  
                     }  
                });  


The following code needs to be added into html code.

 <div id = "result">     </div>  


There are some other bootstrap alert styles. You can find them here.







No comments:

Post a Comment