admin管理员组文章数量:1279014
Is it possible to force an error state to return to an ajax request from a PHP script?
I am handling the success and error states in an ajax request and I want a way to force the error. The error only seems to be triggered by xhttp error and I want to trigger this when a condition is not met at the server. Its seems confusing to have to return success and have to actually put a flag in the response for an error
Is it possible to force an error state to return to an ajax request from a PHP script?
I am handling the success and error states in an ajax request and I want a way to force the error. The error only seems to be triggered by xhttp error and I want to trigger this when a condition is not met at the server. Its seems confusing to have to return success and have to actually put a flag in the response for an error
Share Improve this question edited Oct 16, 2019 at 7:22 Rahul 18.6k7 gold badges42 silver badges63 bronze badges asked Oct 19, 2010 at 20:58 DavidDavid 4151 gold badge6 silver badges9 bronze badges2 Answers
Reset to default 7You 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);
}
});
You can use header to do this, for example:
header('HTTP/1.1 503 Service Unavailable');
本文标签: JavaScriptjQuery and PHP Ajax force an errorStack Overflow
版权声明:本文标题:JavaScriptjQuery and PHP Ajax force an error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741271246a2369339.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论