What is the difference between error () and ajaxError() events in jQuery?


jQuery error() method

The error() method triggers the event when an element encounters an error. This method deprecated in jQuery 1.8.

Example

You can try to run the following code to learn how to work with error() method in jQuery −

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("img").error(function(){
        $("img").replaceWith("<p>Image isn't loading</p>");
    });
    $("button").click(function(){
        $("img").error();
    });
});
</script>
</head>
<body>

<img src="/videotutorials/images/tutorial_library_home.jpg" alt="Video Tutorial" width="300" height="200"><br>

<button>Error event</button>

</body>
</html>

jQuery ajaxError() method

The ajaxError( callback ) method attaches a function to be executed whenever an AJAX request fails. This is an Ajax Event.

Example

You can try to run the following code to learn how to work with ajaxError() method in jQuery −

Live Demo

<html>

   <head>
      <title>jQuery ajaxError() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               /* Assume result.text does not exist. */
               $('#stage1').load('/jquery/result.text');
            });

            $(document).ajaxError(function(event, request, settings ){
               $("#stage2").html("<h1>Error in loading page.</h1>");
            });
               
         });
      </script>
   </head>

   <body>
   
      <p>Click on the button to load result.text file:</p>
       
      <div id = "stage1" style = "background-color:blue;">
         STAGE - 1
      </div>
       
      <div id = "stage2" style = "background-color:blue;">
         STAGE - 2
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>
   
</html>

Updated on: 17-Feb-2020

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements