1

I am gradually enhancing the ajax-tivity (TM) of my site and have recently added in some pretty basic error handling. My calls are being made via the jquery .ajax() method and I display errors to the user with a show_error_box(message) function I am handling all of my ajax by returning scripts so server-side validation was easy - I just send back a call to show_error_box. For other errors I have simply put the following code in my .ajax call

error: function(xhr, status, error) {
    show_error_box("There has been an error communicating with the server<br/>The field has not been updated<br/>Please check your internet connection");
}

I've found that this deals nicely with most issues (no connection, timeout, etc) but it deals poorly with the situation when a user clicks on a link while an ajax call is still in progress. The error box begins to display and then suddenly the user is whisked away to the new page.

What is the better way of handling this situation? I would ideally like a non-intrusive error message displayed (e.g. 'please wait until the update is finished') and the click on the link ignored. Any suggestions as to how to best achieve this?

EDIT:

I solved this by temporarily disabling all links then reenabling them like so;

$.ajaxSetup({  
    beforeSend: function() {disable_links()},
    complete: function() {enable_links()},
    timeout: 15000
});

function disable_links() {
    $('a').each(function() {
        if ($(this).attr('href')) {
          $(this).data('href', $(this).attr('href')).removeAttr('href');
      }
    })
}

function enable_links() {
    $('a').each(function() {
        $(this).attr('href', $(this).data('href'));
    })
}
brad
  • 9,573
  • 12
  • 62
  • 89
  • 2
    See [jQuery $.ajax calls success handler when request fails because of browser reloading](http://stackoverflow.com/questions/4553124/jquery-ajax-calls-success-handler-when-request-fails-because-of-browser-reload?rq=1) where a `beforeunload` handler is suggested. Beware that `beforeunload` doesn't work on iOS / Mobile Safari, though. – Peter V. Mørch Aug 07 '13 at 12:30

1 Answers1

1

Maybe you can use the BlockUI jQuery plugin. This will prevent the user from clicking links until the current AJAX request returns:

$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • I had a look but found the plugin too intrusive. I found a solution that works for me and have put it in my edit. Thanks. – brad Feb 01 '11 at 10:35