PHP + Ajax 登录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14449118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP + Ajax Login
提问by JPDP
Just having a few issues submitting a login form via ajax, I am primarily a PHP developer, I don't use Jquery + Ajax all that often with PHP.
只是在通过 ajax 提交登录表单时遇到一些问题,我主要是一名 PHP 开发人员,我不经常在 PHP 中使用 Jquery + Ajax。
At the moment If i check the firebug POST data after the form has been submit it does appear to get the username and password that have been added to the form, however the page just reloads regardless of whether an incorrect username and password are added or if they are correct and no session is created.
目前,如果我在提交表单后检查 firebug POST 数据,它似乎确实获取了已添加到表单中的用户名和密码,但是无论是否添加了不正确的用户名和密码,页面都会重新加载它们是正确的,并且没有创建会话。
This is the form:
这是表格:
<form id="loginform" method="post">
Username: <input type="text" name="username" id="username" value="">
Password: <input type="password" name="password" id="password" value="">
<input type="submit" name="loginsub" id="loginsub" value="Login">
</form>
This is the Ajax/Jquery:
这是 Ajax/Jquery:
<script type="text/javascript">
$(document).ready(function() {
$('#loginform').submit(function() {
$.ajax({
type: "POST",
url: '/class/login.php',
data: {
username: $("#username").val(),
password: $("#password").val()
},
success: function(data)
{
if (data === 'Login') {
window.location.replace('/user-page.php');
}
else {
alert('Invalid Credentials');
}
}
});
});
});
</script>
And this is the PHP:
这是PHP:
class Users {
public $username = null;
public $password = null;
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
$this->__construct( $params );
}
public function Login() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$user = username;
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", md5($this->password), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
session_start();
session_regenerate_id();
$_SESSION['user'] = $user['user'];
session_write_close();
echo ('Login');
exit();
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}
I guess it is not working because I am not calling the class and function, but I am not sure how to succesfully do so. I tried creating a controller page in between the 2 that would initiate the php class and function but to no avail.
我想它不起作用,因为我没有调用类和函数,但我不确定如何成功调用。我尝试在 2 之间创建一个控制器页面,该页面将启动 php 类和函数,但无济于事。
Just to edit, the login does work correctly if I remove the ajax and just call the php page via the login form action.
只是为了编辑,如果我删除 ajax 并通过登录表单操作调用 php 页面,登录确实可以正常工作。
Any ideas?
有任何想法吗?
回答by Jakub Riedl
whole issue is in jquery use this instead
整个问题是在 jquery 中使用它来代替
$(document).ready(function() {
$('#loginform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/class/login.php',
data: $(this).serialize(),
success: function(data)
{
if (data === 'Login') {
window.location = '/user-page.php';
}
else {
alert('Invalid Credentials');
}
}
});
});
});
回答by Jens Peters
$user = new User(array("username" => $_POST['username'], "password" => $_POST['password']));
$user->Login();
Put the code above into an login.php controller file (including your users class). Or write a general controller that handles the requests.
将上面的代码放入 login.php 控制器文件(包括您的用户类)。或者编写一个处理请求的通用控制器。
回答by Mahedi Hasan Durjoy
$(document).ready(function(){
$("#submit").click(function(){
var email = $("#email").val();
var password = $("#password").val();
if(email.length == "" || password.length == ""){
$("#message").html("please fill out this field first").fadeIn();
$("#message").addClass("error");
return false;
}else{
$.ajax({
type : 'POST',
url : 'redirect.php',
data : {email:email,password:password},
success : function(feedback){
$("#text").html(feedback);
}
});
}
});
$(".email_error_text").hide();
$(".password_error_text").hide();
var error_email = false;
var error_password = false;
$("#email").focusout(function(){
check_email();
});
$("#password").focusout(function(){
check_password();
});
function check_email(){
$("#message").hide();
var pattern = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
if(pattern.test($("#email").val())){
$(".email_error_text").hide();
}else{
$(".email_error_text").html("Invalid email address");
$(".email_error_text").show().addClass("error");
error_email = true;
}
}
function check_password(){
$("#message").hide();
var password_length = $("#password").val().length;
if(password_length < 8 ){
$(".password_error_text").html("Should be at least 8 characters");
$(".password_error_text").show().addClass("error");
error_password = true;
}else{
$(".password_error_text").hide();
}
}
});
});
I will refer you to go here to read this article login with ajax & php
我会推荐你去这里阅读这篇文章使用ajax和php登录

