When a user submits invalid data to my API (usually via Javascript + JSON), I am wondering which HTTP response code I should reply with.
Should I return a HTTP 200 response with the errors - or should my server respond with a 400 or 500 error since the request actually failed my validation because of some bad data?
It seems like a 400 error is the way to go since "The 4xx class of status code is intended for cases in which the client seems to have erred" - wikipedia
However, one thing to keep in mind is that most people use a framework like jQuery which requires you to specify an alternate callback when AJAX requests respond with any status code other than a 200.
400 Bad Request The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
use statusCode in jquery ajax calling:
<html>
<head>
<title>jquery testing</title>
<script type="text/javascript" src="jquery-1.6.2.min.js"/>"></script>
<script language="javascript">
$(document).ready(
function(){
$('#linkClick').click(
function(){
$.ajax({
url: 'a.html',
data: {},
type: 'get',
dataType: 'json',
statusCode: {
404:function() { alert("404"); },
200:function() { alert("200"); },
201:function() { alert("201"); },
202:function() { alert("202"); }
},
success: function(data) {
alert( "Status: " + data);
}
});
});
}
);
</script>
</head>
<body>
<a href="#" id="linkClick">click</a>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With