简体   繁体   English

AJAX jQuery php登录表单

[英]AJAX jQuery php Login form

hello i have a little bit of a trouble finding a specific answer so .. i hope this is not a repost, i have the following login.php code 你好,我在寻找具体答案时有点麻烦,所以..我希望这不是重新发布,我有以下login.php代码

function loginBackUser($arr){
global $link;
extract($arr);
$msg = '';
$pass = md5($pass);
$pass = md5($pass);
$pass = sha1($pass);
$pass = md5($pass);
$pass = md5($pass);
$pass = sha1($pass);
$pass = sha1($pass);
$pass = sha1($pass);
$sql = "SELECT * FROM `table` WHERE `email`='$email' AND `pass`='$pass'";
$sqlEmail = "SELECT * FROM `table` WHERE `email`='$email'";
$resEmail = mysqli_query($link,$sqlEmail) or die("SQLEmail gresit");
$res = mysqli_query($link,$sql) or die("SQL gresit");
if(mysqli_num_rows($res) == 1){
    $row = mysqli_fetch_assoc($res);
    session_start();
    $id=$row['id'];
    $_SESSION['id'] = $row['id'];
    $_SESSION['name'] = $row['name'];
    $sqlEmptyAttempts = "UPDATE `table` SET `attempts` = '0' WHERE `id` = '$id'";
    $resEmptyAttempts = mysqli_query($link,$sqlEmptyAttempts) or die("SQLEmptyAttempts gresit");
    header('Location:/oproit/index.php?pag=dash_homepage');
}else if(mysqli_num_rows($resEmail) == 1){
    $row2 = mysqli_fetch_assoc($resEmail);
    $id=$row2['id'];
    $sqlVerifyAttempts = "SELECT `attempts` FROM `table` WHERE `id` = '$id'";
    $resVerifyAttempts = mysqli_query($link,$sqlVerifyAttempts) or die("SQLVerifyAttempts gresit");
    $row3 = mysqli_fetch_assoc($resVerifyAttempts);
    if($row3['attempts']<3){
        $attempts = $row3['attempts']+1;
        $sqlSetNewAttempts = "UPDATE `table` SET `attempts` = '$attempts' WHERE `id` = '$id'";
        $resSetNewAttempts = mysqli_query($link,$sqlSetNewAttempts) or die("SQLSetNewAttempts gresit");
        echo "wrong password";
    }else{
        $sqlEmptyAttempts = "UPDATE `table` SET `attempts` = '0' WHERE `id` = '$id'";
        $resEmptyAttempts = mysqli_query($link,$sqlEmptyAttempts) or die("SQLEmptyAttempts gresit");
        echo "dude be serious"; // here will be some mail function but for now i just want it to work with ajax
    }
}else{
    echo "your email is not in our data base";
}

$thread_id = mysqli_thread_id($link);
mysqli_kill($link,$thread_id);
mysqli_close($link);
}

i would like it to be accessed by axaj, and my "echos" to be inside a previously empty div, the login form html page 我希望它可以被axaj访问,而我的“ echos”位于以前为空的div内,登录表单html页

<form id="loginUser" method="post" action="login.php" onsubmit="return false;">
<input type="text" id="email" name="email" class="textField" value="email" />
<input type="password" id="pass" name="pass" class="textField" value="" />
<input type="submit" id="loginUserSubmit" onclick="isSession('loginUser','resultShow')" name="loginUserSubmit" value="Da Bah!" /></form><div id="resultShow">sas</div>

my so far javascript is 我到目前为止的javascript是

function isSession(selector,responseElement) {
    var e = document.getElementById(selector);
    if(!e){
        alert('there is no element with the id='+selector);
    }
    var b = document.getElementById(responseElement);
    if(!b){
        alert('there is no element with the id='+responseElement);
    }
    $(e).submit(function (event) {
        $.ajax({
            type: $(e).attr('method'),
            url: $(e).attr('action'),
            data: $(e).serialize(),
            success: function(data){
                $(b).html(data);
            },
            error: function() {
                alert("Error occured")
            }
        });

        event.preventDefault();
    });
}

but it does nothing .. i need when the user clicks the login button and gets only the pass wrong .. to let him be wrong for three times .. but at every turn tell him . 但是它什么也没做..当用户点击登录按钮并且仅得到错误的通行证..让我错了三遍..但总是告诉他的时候。 in that empty div .. that he was wrong... 在那个空的div中..他错了...

Do you know what i mean? 你懂我的意思吗?

The problem is on your PHP (login.php). 问题出在您的PHP(login.php)上。

You should remove the function loginBackUser : you're not calling that method. 您应该删除函数loginBackUser :您不调用该方法。 And change the extract method on login.php to extract($_POST) . 并将login.php上的extract方法更改为extract($_POST)

eg: 例如:

<?php
if (isset($_POST['pass']) && isset($_POST['email'])) {
    global $link;
    extract($_POST);
    ...
}

EDIT 编辑

This isn't the best way to make a login system, I hope you are just studying/testing :) 这不是制作登录系统的最佳方法,我希望您只是在学习/测试:)

so ... in stead of using ajax which i don't know that well, i made something that might be called unprofessional by others, which is <div id="resultShow"> <?php if(isset($_POST['loginUserSubmit'])){ require_once('/path/to/Class.BackUser.php'); $bkUser = new BackUser(); $bkUser->loginBackUser($_POST); } ?> </div> 所以...代替了我不太了解的ajax,我做了一些可能被其他人称为不专业的事情,它是<div id="resultShow"> <?php if(isset($_POST['loginUserSubmit'])){ require_once('/path/to/Class.BackUser.php'); $bkUser = new BackUser(); $bkUser->loginBackUser($_POST); } ?> </div> <div id="resultShow"> <?php if(isset($_POST['loginUserSubmit'])){ require_once('/path/to/Class.BackUser.php'); $bkUser = new BackUser(); $bkUser->loginBackUser($_POST); } ?> </div> <div id="resultShow"> <?php if(isset($_POST['loginUserSubmit'])){ require_once('/path/to/Class.BackUser.php'); $bkUser = new BackUser(); $bkUser->loginBackUser($_POST); } ?> </div> and this way .. whatever the method loginBackUser() echos, is in the place that i wanted it to be, but i would still like with your help, if you will, to find a way to skip that refresh php needs to do everything :D <div id="resultShow"> <?php if(isset($_POST['loginUserSubmit'])){ require_once('/path/to/Class.BackUser.php'); $bkUser = new BackUser(); $bkUser->loginBackUser($_POST); } ?> </div>这样,.loginBackUser()方法所响应的地方就是我想要的位置,但是如果您愿意,我仍然希望在您的帮助下找到一种跳过方法刷新PHP需要做的一切:D

I'm not sure how you handle the server side validation but I simplified your code just to make a small demonstration of ajax get/post on same page. 我不确定您如何处理服务器端验证,但是我只是为了在同一页面上进行ajax get / post的简短演示而简化了代码。 This is just an example and can be done in many other ways. 这仅是示例,并且可以通过许多其他方式来完成。

From .serialize() documentation: .serialize()文档中:

No submit button value is serialized since the form was not submitted using a button. 由于没有使用按钮提交表单,因此没有序列化提交按钮的值。

Here's the full code I came up with 这是我想出的完整代码

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<?php
  if(isset($_POST["email"]) && isset($_POST["pass"]))
  {
    echo "Email:".$_POST["email"]."<br/>Password:".$_POST["pass"];
  }
  else
  {
?>
<form id="loginUser" method="post" action="login.php">
<input type="text" id="email" name="email" class="textField" value="email" />
<input type="password" id="pass" name="pass" class="textField" value="" />
<input type="submit" id="loginUserSubmit" name="loginUserSubmit" value="Da Bah!" />
</form><div id="resultShow"></div>
<script>
$(document).ready(function(){
    $("#loginUser").submit(function (event) {
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(data){
                $("#resultShow").html(data);
            },
            error: function() {
                alert("Error occured")
            }
        });
        event.preventDefault();
    });
});
</script>
<?php
  }
?>
</body>
</html> 

You should make a reference to jQuery library with 您应该使用以下内容来引用jQuery库

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Always better to wrap your script in $(document).ready() function like this 总是最好将脚本包装在$(document).ready()函数中

$(document).ready(function()
{
  //your code here
}
);

In your case, it's as follows 您的情况如下

$(document).ready(function(){
    $("#loginUser").submit(function (event) {
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(data){
                $("#resultShow").html(data);
            },
            error: function() {
                alert("Error occured")
            }
        });
        event.preventDefault();
    });
});

On server-side there are many ways to see if the form was posted or not. 在服务器端,有很多方法可以查看表单是否已发布。 Simply use 只需使用

if(isset($_POST["email"]) && isset($_POST["pass"]))

and wrap your logic in it. 并在其中包装您的逻辑。 If the form was not submitted do something else. 如果未提交表单,请执行其他操作。

Give this a try and if that works, implement the validations along with extras on the working version. 试试看,如果可行,在工作版本上实施验证以及其他功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM