The most simple way could be to use just call an url that actually returns that code like so:
$.ajax({
url: 'https://httpstat.us/400',
type: 'POST',
// further arguments
}).done(function (result) {
console.log("Success");
}).fail(function(result) {
console.log("Fail");
console.log("Result", result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But you can also, based on this answer, override the $.ajax()
function to always fail like so:
function ajax_fail(jqXHR, textStatus, errorThrown) {
return function (params) {
var deferred = $.Deferred().reject(jqXHR, textStatus, errorThrown);
return deferred.promise();
}
}
$.ajax = ajax_fail();
$.ajax({
url: '',
type: 'POST'
}).done(function (result) {
console.log("Success");
}).fail(function (result) {
console.log("Error");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The parameters you pass to the ajax_fail()
function will be the ones your .fail()
callback will add. You can add there whatever you like to be returned.
Small warning: Don't use this in production or if you still want other $.ajax
calls to work. Every time you call $.ajax()
it will fail this way.
If you want to only do this for one AJAX call, do something like this:
var ajaxFunc = $.ajax;
// use the above code
// restore old $.ajax function
$.ajax = ajaxFunc;