How to Implement jQuery Ajax Error handling in ASP.NET MVC Project

This article is for solving a problem of jquery ajax error facing in Asp.Net MVC projects.

The problem with Ajax Errors:

During in asp.net programming, We have plenty of Ajax methods in our asp.net MVC project. The problem is that some methods were broken. so that, we having not get exactly in which methods the issue was arises. this is actually because of jquery ajax error.

The solution for Ajax Errors:

We can solve issues two ways:

  • Handling error for individual methods.
  • Handling error using a single(Global) method.

If we handle error for individual methods. it will take lots of efforts for us to put error handling code in individual methods. Another approach for handle code using global method.

Examples :

  1.  Handling error using a single(Global) method:
 $(document).ajaxError(function( event, jqxhr, settings, thrownError ) {
        if ( settings.url == "ajax/missing.html" ) {
               $( "div.log" ).text( "Triggered ajaxError handler." );
           }
 });

Parameters:

settings: settings object that was used in the creation of the request information such as settings.url.
thrown Error: receives the textual portion of the HTTP status, such as “Not Found” or “Internal Server Error.”

  •  Handling error for individual methods:
$.ajax({
      type: "POST",
      url: "some/url",
      success: function(data, status, xhr) {
         // handle success
      },
      error: function(xhr, status, error) {
           // handle error
}});

Conclusion :

We can handle ajax error two ways one for an individual method. one for using a single global method so it is good practice if we handle ajax.error method globally rather than doing code for the individual method. There are many global Ajax methods such as follow:

  • .ajaxComplete()
  • .ajaxError()
  • .ajaxSend()
  • .ajaxStart()
  • .ajaxStop()
  • .ajaxSuccess()

Please check below link For reference, see how it is written:

http://api.jquery.com/ajaxError/

Kindly visit our latest articles related for Asp.net MVC using c# programming and much more.

Thanks.

By | 2017-01-06T18:31:24+00:00 October 3rd, 2016|Asp.Net, Asp.Net MVC, How To|