JavaScript
Article
By Sam Deering

jQuery Ajax Error Handling Function

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

jQuery Ajax Error Handling Function

$( document ).ajaxError(function( event, request, settings ) {
  $( "#msg" ).append( "
  • Error requesting page " + settings.url + "
  • " ); });

    Offical .ajaxError() API

    Note: If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxError() method will not fire.

    Below is an older function which you can get the status from the jqXHR object.

    --ADVERTISEMENT--

    $(function() {
        $.ajaxSetup({
            error: function(jqXHR, exception) {
                if (jqXHR.status === 0) {
                    alert('Not connect.n Verify Network.');
                } else if (jqXHR.status == 404) {
                    alert('Requested page not found. [404]');
                } else if (jqXHR.status == 500) {
                    alert('Internal Server Error [500].');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                    alert('Uncaught Error.n' + jqXHR.responseText);
                }
            }
        });
    });
    Login or Create Account to Comment
    Login Create Account
    Recommended
    Sponsors
    Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?