4

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 Answer 1

6

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

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

...or if the #msg element is present the entire time, you can do this:

$('#msg').ajaxError(function() {
  $(this).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:

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

Note: in previous versions of jQuery this would be done via $.ajaxError(), since 1.7 that's no longer the case, you'll need to attach it to a jQuery object you want it on, or document if you don't care about a particular element.

Sign up to request clarification or add additional context in comments.

3 Comments

$.ajaxError is "not found" in jQuery 1.7.1. $(document).ajaxError works though...
$.ajaxError(function() doesnt work, as pointed out. Has to be attached to element, like "document"
@Aleja_Vigo - indeed, this is a breaking change in jQuery long after this answer was posted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.