You can approach this from two sides:
- Force an error by calling an HTTP header, such as 404 or 503.
- Force an error based on the specific state of the received data.
, HTTP, , 404 503:
PHP
<?php
if(User::Login($_POST['username'], $_POST['password'])) {
print 'Login successful!';
} else {
header("HTTP/1.0 403 Forbidden");
print 'Bad user name / password';
}
JQuery
$.ajax({
'url': '/some/url',
'type': 'POST',
'data': {
'username': 'someone@example.com',
'password': 'rhd34h3h'
},
'success': function(data) {
alert(data);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + textStatus);
}
});
, :
PHP
<?php
$return = array();
if(User::Login($_POST['username'], $_POST['password'])) {
$return['success'] = True;
$return['message'] = 'Login successful!';
} else {
$return['success'] = False;
$return['message'] = 'Bad user name / password';
}
print json_encode($return);
JQuery
$.ajax({
'url': '/some/url',
'type': 'POST',
'dataType': 'json',
'data': {
'username': 'someone@example.com',
'password': 'rhd34h3h'
},
'success': function(data) {
if(data['success']) {
alert(data['message']);
} else {
this.error(this.xhr, data['message']);
}
},
'error': function(jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + textStatus);
}
});