我正在学习网络开发课程。目前,我正在建立一个可供人们做笔记的网页。我的注册表单运行正常,激活有效,使用用户名和密码创建了数据库值。问题是,当尝试使用激活的用户名和密码登录时,它不会重定向到我的登录页面。我尝试了很多事情,只是找不到问题所在。我测试了我与数据库的连接,一切似乎都正常了。我将代码与课程老师进行了比较,但没有发现任何区别。但是,他的作品,我没有。感谢您的任何建议!
这是我用Ajax调用登录表单的代码
$("#loginform").submit(function (event) {
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "login.php",
type: "POST",
data: datatopost,
success: function (data) {
if (data == "success"){
window.location = "mainpageloggedin.php";
}else{
$("#loginmessage").html(data);
}
},
error: function () {
$("#loginmessage").html("<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later!</div>");`
}
});
});
<?php
session_start();
//Connect to database
include("connections.php");
//Check user inputs
// Define error messages
$missingEmail = '<p><strong>Please enter your email!</strong></p>';
$missingPassword = '<p><strong>Please enter a password!</strong></p>';
if(empty($_POST["loginemail"])){
$errors .= $missingEmail;
}else{
$email = filter_var($_POST["loginemail"], FILTER_SANITIZE_EMAIL);
}
//GET PASSWORDs
if(empty($_POST["loginpassword"])){
$errors .= $missingPassword;
}else{
$password = filter_var($_POST["loginpassword"], FILTER_SANITIZE_STRING);
}
if($errors){
$resultMessage = '<div class="alert alert-danger">' . $errors . '</div>';
echo $resultMessage;
}else{
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
$password = hash('sha256', $password);
$sql = "SELECT * FROM users WHERE email = '$email' AND password='$password' AND activation='activated'";
$result = mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
if($count !== 1){
echo '<div class="alert alert-danger">Wrong username or password</div>';
}
else{
//log the user in: set session variables
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id']=$row['user_id'];
$_SESSION['username']=$row['username'];
$_SESSION['email']=$row['email'];
// header('location: mainpageloggedin.php');
}
}
?>
谢谢
答案 0 :(得分:0)
使用serialize
而不是serializeArray
提交表单:
$("#loginform").validate({
rules: {
loign_email: {
required: true,
email: true
},
login_password: {
required: true,
},
},
messages: {
login_password: "Please enter a valid password",
loign_email: "Please enter a valid email address",
},
submitHandler: function(form) {
$.ajax({
url: "login.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (data) {
if (data == "success"){
window.location = "mainpageloggedin.php";
}else{
$("#loginmessage").html(data);
}
},
error: function () {
$("#loginmessage").html("<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later!</div>");`
}
});
});