JQuery Ajax with ajaxerror

From CoderLearner
Jump to: navigation, search

Description

Whenever an Ajax request is completed but with an error, it will triggers the $.ajaxError() event to be sent.

Example 1

This example shows how the $.ajaxError event trigger when we try to send ajax request with the invalid or non-existed server side script.

<!DOCTYPE html>
<html>
   <head>
      <title>ajax</title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <script 
         type="text/javascript" 
         src="/lib/jquery-1.7.2.min.js">				 
      </script>
      <script>
         $(document).ready(function() {
            $('form[name="frm_userinfor"]').submit(function(){
               var agev = $('input[name="age"]').val();
         // it will never send, because age.php2 is not existed
               $.post('age.php2',{'age':agev},
               function(data){
                  if(data=='failed'){
                     $('#content').html('Something wrong, please try again!');
                  }
                  else {
                     $('#content').html(data);
                  }
               });
               
               return false;
            });
            // when an ajax request completes and with an error, 
            // it will trigger this $.ajaxError 
            $('#content_progress').ajaxError(function(){
               $(this).html('Invalid Request');
               $(this).fadeIn();
            });
           
         });
      </script>
   </head>
   <body>
      <div id="content_progress"></div>
      <div id="content"></div>
      <form name="frm_userinfor" method="post">
         Age:<input type="text" name="age"/><br/>
         <input type="submit" name="check" value="Check" />
      </form>
   </body>
</html>

Try It