我已经使用ajax和php创建了登录和注册页面。某些用户给我发送了电子邮件“我们无法注册”。但是我看到它们已经从数据库中注册了。注册后不会重定向用户。有时会说这个问题是他们在计算机上看到的,但是可以多次移动。
我想知道我是否错过了一个错误,您愿意帮我吗?
Ajax代码:
<script type="text/javascript">
$(document).ready(function(){
var form = $('#registerform');
var submit = $('#register');
var firstname = $('#register_username');
var fullnamereg = $("#reg_fullname");
var regemail = $('#reg_email');
var regpassword = $('#reg_password');
var validated = true;
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
jQuery.ajax({
type: "POST",
url: URL+"register.php",
data: form.serialize(),
beforeSend: function(){},
success:function(data){
if($.trim(data) === 'ok'){
setTimeout(function() {
$('.login_form').html("Registered!");
setTimeout(function() {
window.location.href = siteurl;
}, 1000);
}, 1000);
}
},
error: function(data){
$('#form_error').html('Error, intenta de nuevo.');
},
})
});
});
</script>
和PHP代码在这里:
if(isset($_POST["reusername"]) && isset($_POST["fullname"]) && isset($_POST["password"]) && isset($_POST["regemail"])){
$firstname = mysqli_real_escape_string($db, $_POST["reusername"]);
$fullname = mysqli_real_escape_string($db, ucfirst(strtolower($_POST["fullname"])));
$password = mysqli_real_escape_string($db, sha1(md5(trim($_POST["password"]))));
$thisEmail = mysqli_real_escape_string($db, $_POST['regemail']);
$registerTime = time();
$ip=$_SERVER['REMOTE_ADDR']; // user ip
$saveUser = mysqli_query($db,"INSERT INTO `users`
(email,username,fullname ,password,registered,ip)
VALUES
('$thisEmail','$firstname','$fullname','$password','$registerTime','$ip')") or die(mysqli_error($db));
if($saveUser){
$getUserID = mysqli_query($db,"SELECT user_id,username FROM users WHERE email = '$thisEmail' AND username = '$firstname'") or die(mysqli_error($db));
$row=mysqli_fetch_array($getUserID,MYSQLI_ASSOC);
$uid=$row['user_id']; // Get User ID
$dbunm = $row['username']; // Get User Username
$_SESSION['user_id'] = $uid; // Session User ID
$hash = sha1($dbunm).$registerTime;
if($hash){
setcookie($cookiename,$hash,time()+31556926 ,'/');
mysqli_query($db, "INSERT INTO `session` (userid, auth) VALUES ('$uid', '$hash')");
echo 'ok';
}
}
}
答案 0 :(得分:0)
如果由于用户已经存在而导致插入失败,则PHP代码将返回200成功状态,但不会回显ok
。因此,您的Javascript代码将落入成功块,但随后跳过if语句。因此,如果用户尝试重新注册,他们将不会收到任何错误消息和重定向。您可能使PHP代码发出了明确的错误状态:
if($saveUser){
...
} else {
http_response_code(500);
exit;
}
然后,如果注册失败,则AJAX调用将落入错误块。