尝试使用 AJAX 创建登录表单,因此无需更改页面即可登录用户。到目前为止,在使用我发现的教程后,我得到了以下内容,但是我遇到的问题是表单正在重新加载页面而不是调用JavaScript 函数。
HTML:
<form class="login-form" onSubmit="check_login();return false;">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn trans login-button">Login</button>
</form>
PHP:
// Retrieve login values from POST variables
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
// Salt and hash password for database comparison
$password = saltHash($password);
// Check that both fields are not empty
if(!empty($email) || !empty($password)) {
// Query database to check email and password match entry
$database->query('SELECT * FROM users WHERE email = :email AND password = :password');
$database->bind(':email',$email);
$database->bind(':password',$password);
$result = $database->single();
if(!empty($result)) {
// Check entered details match the database
if($email == $result['email'] && $password == $result['password']) {
// If login details are correct, return 1
echo '1';
}
}
else {
// If not returned results, return 2
echo '2';
}
}
else {
// If either fields are empty, return 3
echo '3';
}
JavaScript / jQuery:
// Login function
function check_login() {
$.ajax({
type: 'POST',
url: 'check-login.php',
data: 'email=' + $('input[value="email"]').val() + '&password=' + $('input[value="password"]').val(),
success: function(response){
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
任何帮助是极大的赞赏。