qglzla
Last Updated: February 25, 2016
·
1.627K
· lukemadhanga

jQuery UI Tabs - Handle AJAX failures when loading a page

Playing with large data (e.g. statistics) and displaying this data via an AJAX request, I gathered that users would get impatient and need some way of knowing that the page was still loading, so I added a loading GIF on the page which prevented further actions until the page was loaded. This was pretty easy considering the beforeLoad and load properties in the tabs ui function. When there was an AJAX error however, the GIF kept spinning and the user had no way of knowing (unless they opened devtools). This is because jQuery UI doesn't have fail option. However, a few console.log reveals that the second object passed to you in the beforeLoad function is the original jqXHR (AJAX) object that jQuery used to make the AJAX call. One can use this object to add in a feature that really should have been there from the beginning, so here goes:

$('#tabs').tabs({
    beforeLoad: function(event, ui) {
        ui.jqXHR.fail(function (e) {
            // We have failed to load the tab content
        });
        if (ui.panel.html().length) {
            // We have already loaded this tab, don't attempt to load it again
            return false;
        }
    },
    load: function() {
        // We have loaded. Remove the loading animation from the screen
    }
});

The ui.jqXHR.fail is synonymous with the fail in $.ajax().fail().

Enjoy