sirjohn
sirjohn

Reputation: 69

how can i handle multiple ajax errors in jquery

I want my error function to work in a specific way such that it should display error corresponding to the json file that is not laded. I want error function to display massages like business.json not loaded, Energy.json not loaded, accordingly when I click on any of the corrisponding link "business", "energy", etc.

The key variable holds the value for each json file. For example it would have business.json if i click "business" link on my page

my code is:

$.ajax({
    url: "./"+key + "?"+ new Date().getTime(),
    dataType: 'json',
    success: function(courses){
        currentResults=courses;
        populateSubCat();
        $("#kss-spinner").css({'display':'none'});
    },
    error: function(key) {  
        //console.log(xhr.Status);

        if(key != "business.json"){
            console.log('business.json not loaded ');
        }
    }
});

Upvotes: 1

Views: 1159

Answers (1)

palaѕн
palaѕн

Reputation: 73966

Try this:

jQuery Ajax Error Handling Function

$(function() {
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
});

After that call your ajax function, you will get the error details.

Upvotes: 1

Related Questions