How can I return the callback of .fail() if the return dataType is not a html?
$.ajax({
type: "GET",
dataType: "html",
url: "server.php",
async: true,
beforeSend: function() {
},
success: function (returndata) {
console.log(returndata); // I will get {"message":"something"}
}
}).fail(function(jqXHR) { // this callback does not work
alert("error");
});
For instance, in server.php,
header('Content-Type: application/json');
echo '{"message":"something"}';
I will get {"message":"something"} instead of error;
any ideas?
edit:
$.ajax({
type: "GET",
dataType: "xml",
url: "server.php",
async: true,
beforeSend: function() {
},
success: function (returndata) {
console.log(returndata); // I will get {"message":"something"}
}
}).fail(function(jqXHR) { // this callback does not work
alert("error");
});
if I change the dataType: to "xml", it will return the error (which is what I want) when it is expected xml - why does it not work in the same way for "html"?
Check whether your server responds JSON as plain text encoding or application/JSON. If it is JSON, use error() method instead fail(). It will go to error method if content type mismatches. Here is an example.
Above code will work fine with error method and go to error if content type is html. Try this in your scenario.