2 回答
TA贡献1868条经验 获得超4个赞
首先,如果您从 javascript 请求某些内容,则无法通过 php 重定向用户,请从 addUser.php 中删除此行
header('Location: ./dashboard.php?user='.$username);
现在要将结果从 php 返回到客户端,您必须DIE使用带有值的 php,最好的方法是 JSON
在 addUser.php 检查你想要什么并返回如下值:
<?php
session_start();
/* Include the database connection file (remember to change the connection parameters) */
require './db_inc.php';
/* Include the Account class file */
require './account_class.php';
$type = $_POST['type'];
$username = $_POST['uname'];
$password = $_POST['password'];
$comp = $_POST['company'];
$email = $_POST['email'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = $pdo->query("SELECT * FROM accounts WHERE email ='".$email."'");
$account = new Account();
// Will print all the values received.
$newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);
if(intval($newId) > 0) // if user created
die(json_encode(array('status' => 'ok')));
else
die(json_encode(array('status' => 'error')));
?>
然后更改您的客户端,如下所示:
$(document).on('click', '#createUserBtn', function(e){
e.preventDefault();
$.ajax({
url:'addUser.php',
type:'post',
data:$('#addUser').serialize(),
dataType: "json", // <- Add this line
success:function(response){ // <- add response parameter
//Here check result
if(response['status'] == 'ok')
toastr.success("User successfully added!");
else
toastr.warning('Uh-oh! Something went wrong with adding this user!');
},
error: function(){
},
statusCode: { // <- Add this property
500: function() {
toastr.warning('Uh-oh! Something went wrong with adding this user!');
}
}
});
});
TA贡献1848条经验 获得超10个赞
您可以使用http_response_code()返回 HTTP 错误代码(通常代码 500 :内部服务器错误)。
您可以使用 try/catch 块来做到这一点:
try
{
...
$account = new Account();
// Will print all the values received.
$newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);
header('Location: ./dashboard.php?user='.$username);
}
catch(Exception $e)
{
http_response_code(500);
exit();
}
- 2 回答
- 0 关注
- 79 浏览
添加回答
举报