我有一个添加新用户帐户的 php 脚本。addAccount() 的一部分检查用户名是否有效,如果无效,则返回不可用的异常(出现致命错误)。我的问题是 AJAX 将一切都解释为成功并无论如何都显示成功消息。如何解决此问题或至少捕获致命错误并显示正确的消息?
$(document).on('click', '#createUserBtn', function(e){
e.preventDefault();
$.ajax({
url:'addUser.php',
type:'post',
data:$('#addUser').serialize(),
success:function(){
toastr.success("User successfully added!");
},
error: function(){
toastr.warning('Uh-oh! Something went wrong with adding this user!');
}
});
});
添加用户.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);
header('Location: ./dashboard.php?user='.$username);
?>
这是使用的 addAccount 函数...
public function addAccount(string $name, string $passwd, string $comp, string $email, string $fname, string $lname, string $type): int
{
/* Global $pdo object */
global $pdo;
/* Trim the strings to remove extra spaces */
$name = trim($name);
$passwd = trim($passwd);
/* Check if the user name is valid. If not, throw an exception */
if (!$this->isNameValid($name))
{
throw new Exception('Invalid user name');
}
/* Check if the password is valid. If not, throw an exception */
if (!$this->isPasswdValid($passwd))
{
throw new Exception('Invalid password');
}
MYYA
慕桂英546537