tags:

views:

96

answers:

1

I have a bunch of ajax calls that contain success and error conditions like this one:

    $.ajax({
        url: 'Remote/State.cfc'
        ,type: "POST"
        ,data: {
            'method': 'UpdateStateName'
            ,'StateID': StateID
            ,'StateName': StateName
        }
        ,success: function(result){
            if (isNaN(result)) {
                $('#msg').text(result).addClass('err');
            } else {
                $('#' + result + ' input[name="StateName"]').addClass('changed');
            };
        }
        ,error: function(msg){
            $('#msg').text('Connection error').addClass('err');
        }
    });

All the error conditions are the same. In other words, they all put the phrase "Connection error" in the msg id.

Q1: Could I remove all these and replace them with

$().ajaxError(function(myEvent, request, settings, thrownError) {
    $('#msg').text('Connection error').addClass('err');
});

Q2: How would you use myEvent and request to display a more informative error message?

+1  A: 

Q1. You can use $.ajaxError() like this:

$.ajaxError(function() {
  $('#msg').text('Connection error').addClass('err');
});

Q2. You can use the handler's arguments that ajaxError passes in, it uses this format: handler(event, XMLHttpRequest, ajaxOptions, thrownError), something like this:

$.ajaxError(function(event, request, options, error) {
  $('#msg').addClass('err')
     .text('Connection error: ' + error + ' when connecting to ' + options.url);
});
Nick Craver