Jquery $.ajax statusCode Else

Steve picture Steve · Apr 6, 2012 · Viewed 33.2k times · Source

In a jquery Ajax call I am currently handling statusCode of 200 and 304. But I also have "Error" defined" To catch any Errors that could come back.

If there is a validation message related we return the status code of 400 - Bad Request.

This then falls into the "Error" function before falling into the statusCode "400" function I had defined. Which means two actions happen.

Ideally I would like to not define "Error" and "Success" and only define "statusCode" But what I need is to have a "Else" so that I don't need to declare every statusCode that exists only the 2-3 I want to handle differently.

$.ajax({
        type: 'POST',
        contentType: "application/json",
        url: "../API/Employees.svc/" + EmployeeId + "/Company/" + CompanyId,
        data: jsonString,
        statusCode: {
            200: function () { //Employee_Company saved now updated

                hideLoading();
                ShowAlertMessage(SaveSuccessful, 2000);
                $('#ManageEmployee').dialog('close');

            },
            304: function () { //Nothing to save to Employee_Company

                hideLoading();
                $('#ManageEmployee').dialog('close');

                if (NothingToChange_Employee) {
                    ShowAlertMessage(NothingToUpdate, 2000);
                } else {
                    ShowAlertMessage(SaveSuccessful, 2000);
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            AjaxError(XMLHttpRequest, textStatus, errorThrown);
        }
    });

Answer

Nicola Peluchetti picture Nicola Peluchetti · Apr 6, 2012

Since the "complete" event is always fired you could simply get the status code from there and ignore the success and error functions

complete: function(e, xhr, settings){
    if(e.status === 200){

    }else if(e.status === 304){

    }else{

    }
}