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);
}
});
This is what i'd use:
To keep the approach similar to your initial logic, I would continue passing a statusCode object. However, you still know that "else" will fall in the realm of 4xx or 5xx type error codes.
So I would update your original code to:
jQuery AJAX response
complete
,success
,error
have been deprecated. More up-to-date version with.done
,.fail
,.always
promise instead.On success
.always
has signature of.done
, on failure it's signature changes to that of.fail
. Using thetextStatus
you can grab the correct variable and return the body contents.Since the "complete" event is always fired you could simply get the status code from there and ignore the success and error functions