3

Possible Duplicate:
jQuery ajax error function

I am trying to replace a "global" ajax error handler with a function that I can call from each ajax call due to problems observed in our implementation.

$(document).ajaxError(function(e, jqXHR, settings, exception) {
    // using BrowserDetect function to get browser info
    var browser    = BrowserDetect.browser;
    var browserVer = BrowserDetect.version;
    var browserOS  = BrowserDetect.OS;
    var ajax_url   = settings.url;
    $.ajax({async: true, 
            type:     'POST',
            url:      AJAX_ERROR_LOG_URL, 
            dataType: 'json',
            data:     'host='myhost.com&status='+jqXHR.status+'&error='+jqXHR.responseText+'&expmessage='+exception.message+'&url=' 
                       +ajax_url+'&browser='+browser+'&browserVer='+browserVer+'&browserOS='+browserOS
    });
    if (jqXHR.status === 0) {
        final_message(ERROR_MSG + '0'); // Not connected. Please verify network is connected.
    } else if (jqXHR.status == 404) {
        final_message(ERROR_MSG + '404'); // Requested page not found. [404]
    } else if (jqXHR.status == 500) {
        final_message(ERROR_MSG + '500'); // Internal Server Error [500].
    } else if (exception === 'parsererror') {
        final_message(ERROR_MSG + '1'); // Requested JSON parse failed.
    } else if (exception === 'timeout') {
        final_message(ERROR_MSG + '2'); // Time out error.
    } else if (exception === 'abort') {
        final_message(ERROR_MSG + '3'); // Ajax request aborted.
    } else {
      if(browserVer == '7' && browser == 'Explorer') {
        final_message(ERROR_MSG + '100'); // Uncaught Error
      } else {
        final_message(ERROR_MSG + '99'); // Uncaught Error
      }
    }
});

I want to convert this to a function and call it like this:

$.ajax({async: true, 
        type:'POST',
        url: url, 
        dataType: 'json', 
        data:     "username="+username+"&password="+pass,
        success:  ajaxLoginResult
        error:    logAjaxError(jqXHR, textStatus, errorThrown)
});

function logAjaxError(jqXHR, textStatus, errorThrown) {
  // more code here to log the error
}

The problem lies in the fact that I cannot get the url of the ajax callpassed to the error callback as the only things that are passed is the jqXHR, textStatus, errorThrown. In the .ajaxError setup, the settings is passed and that is where we get the url from. Any ideas?

Edited 2/3: Here is the Add_Course function for you to see:

function Add_Course(reason) {
  var eventid = $('#eventid'+$('#obleventcode').attr('value')).val();
  var url = AJAX_URL_ADDTOCART + '?sku='+eventid+'&mainitem=true&pid='+pid;
  if(reason != 'VOUCHER'){
    log_url(url);
    $.ajax({async: true, 
            type:'POST',
            url: url, 
            dataType: 'json', 
            success: function(data){
              if(data.result=='success') {
                var cemsg_index=reason.indexOf('CEMSG');
                if(cemsg_index>=0) {
                  final_ce_message(reason.substr(cemsg_index+6));
                } // if(cemsg_index>=0)
              } else {
                $('#sm_content .oblcontent').html(data.message);
              } // if(data.result=='success')
            },
            complete: function(jqXHR, textStatus) {
              log_url('redirecting to cart');
              window.location = CART_URL;
            } // complete
    });
  }
}
Community
  • 1
  • 1
MB34
  • 4,210
  • 12
  • 59
  • 110

2 Answers2

8

First, congratulations on actually checking for errors. So many people write code that never expect things to go wrong on the internets. Ha.

Rather than editing every call to $.ajax you can call $.ajaxSetup() to have every call use your function for an error handler. The error handler signature is error(jqXHR, textStatus, errorThrown) which conveniently matches your function, so try a call to $.ajaxSetup({ error: logAjaxError }) before you do any $.ajax calls.

Jasper
  • 75,717
  • 14
  • 151
  • 146
Dave Methvin
  • 1,458
  • 10
  • 12
  • That is what I'm trying to get out of doing. setting .ajaxError() sets the GLOBAL ajax error handler just like using .ajaxSetup. I do not want to do that. Having it that way causes problems with some of our current code. – MB34 Feb 02 '12 at 21:31
  • I was also reading that the error: part of the $.ajax call is being depricated and you should use it like this var xhr = $.ajax(...) and then check for xhr.fail. Any ideas on that? – MB34 Feb 02 '12 at 21:33
  • Can you explain the problems? – Dave Methvin Feb 02 '12 at 22:30
  • 1
    The error handler is being called when redirecting to another page in the success function of an ajax call. Is there a better way to handle that? – MB34 Feb 02 '12 at 23:16
  • Not sure I am following. You make $.ajax request A, in its success handler you make $.ajax request B, and that request calls its error handler when a 304 redirect occurs? – Dave Methvin Feb 03 '12 at 03:05
  • in function Add_Course a call to log_url function is made; the log_url function also contains an ajax call but it is not the culprit here. After the url is logged, another .ajax call is made and in the success inline function fo that .ajax call, we are redirecting to another URL in the same domain. We are not getting a 304, the .ajax Error is returning a 0 status code with the Exception Message: undefined. I've also had these status codes returned 12031, 12029, 101. I could post a jsFiddle but it wouldn't work because it requires so many other pieces. – MB34 Feb 03 '12 at 15:23
  • I added the Add_Course function to my original post for you to see. – MB34 Feb 03 '12 at 15:25
  • I added a complete function to the ajax in Add_Course and moved the redirect there. I STILL am getting errors when I let processing go through. However, if I set a breakpoint on the redirect code, and then click the continue, I get no error. – MB34 Feb 03 '12 at 17:44
  • Seems like defining a default handler in .ajaxSetup() should work, since that is what you need to do most of the time. For the nested call to $.ajax() in Add_Course just specify a different error handler. If the result is a 304 let it pass, otherwise call the $.ajaxSettings.error handler. – Dave Methvin Feb 05 '12 at 18:24
  • I have decided to ignore the status code 0 and it seems to be working. – MB34 Feb 06 '12 at 17:26
0

You should be able to access this.url on your error callback:

error:    logAjaxError(jqXHR, textStatus, errorThrown, this.url)
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • wanted a "global" ajax error handler, this doesn't do that, sorry. I'd have to write that in each ajax call. – MB34 May 03 '12 at 15:36