You could approach this from two angles:
- Force an error to be thrown by outputting an HTTP header such as a 404 or 503.
- Force an error to be thrown based on certain condition of the resulting data.
Force an error to be thrown by outputting an HTTP header such as a 404 or 503:
PHP
<?php
if(User::Login($_POST['username'], $_POST['password'])) { // Your logic here
print 'Login successful!';
} else {
header("HTTP/1.0 403 Forbidden");
print 'Bad user name / password';
}
jQuery
$.ajax({
'url': '/some/url',
'type': 'POST',
'data': {
'username': '[email protected]',
'password': 'rhd34h3h'
},
'success': function(data) {
alert(data);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + textStatus);
}
});
Force an error to be thrown based on certain condition of the resulting data:
PHP
<?php
$return = array();
if(User::Login($_POST['username'], $_POST['password'])) { // Your logic here
$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': '[email protected]',
'password': 'rhd34h3h'
},
'success': function(data) {
if(data['success']) { // Successful login
alert(data['message']);
} else { // Login failed, call error()
this.error(this.xhr, data['message']);
}
},
'error': function(jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + textStatus);
}
});