A straightforward approach is to simply make a call to a URL that returns the desired code, like this:
$.ajax({
url: 'https://httpstat.us/400',
type: 'POST',
// additional 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>
Alternatively, as mentioned in this answer, you can override the $.ajax()
function to always fail like this:
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 passed to the ajax_fail()
function will be included in your .fail()
callback. You can customize the returned values as needed.
Keep in mind: This method should not be used in production or if you require other $.ajax
calls to succeed. Every instance of $.ajax()
will fail when implemented this way.
If you only want to apply this to a single AJAX call, you can follow these steps:
var ajaxFunc = $.ajax;
// utilize the above code
// restore original $.ajax function
$.ajax = ajaxFunc;