简体   繁体   English

使用jquery,ajax和php登录

[英]Login using jquery, ajax and php

I'm doing a project for the school and I'm having some troubles with this login, I know how to do it in a different way, but I would like to learn how to do it this way. 我正在为学校做一个项目,但登录时遇到了一些麻烦,我知道如何以其他方式进行操作,但是我想学习如何以这种方式进行操作。

I don't really know why its not working (some parts probably don't have any logic and is why its not working), it always says the error message "Invalid credentials" from the alert. 我真的不知道为什么它不起作用(某些部分可能没有任何逻辑,这就是为什么它不起作用),它总是显示警报中的错误消息“无效凭据”。

Here is my code: 这是我的代码:

<html>
<head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#loginform').submit(function(e) {
                e.preventDefault();
                $.ajax({
                    type: "POST",
                    url: 'loginFinal.php',
                    data: $(this).serialize(),
                    success: function(data) {
                        if (data === 'CORRECTO') {
                            window.location = 'index.php';
                        }
                        else {
                            alert('Invalid credentials');
                        }
                    }
                });
            });
        });
    </script>

</head>
<body>
    <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>
</body>
</html>

And here is the PHP: 这是PHP:

function Login() {
        $success = false;           
        try {
            $con = new PDO( 'mysql:host=localhost;dbname=MY_DB_NAME', 'MY_USRNAME', 'MY_PSW' );
            $sql = "SELECT * FROM users WHERE username = ".$_POST['username']." AND password = ".$_POST['password']." LIMIT 1";

            $stmt = $con->prepare( $sql );

            $stmt->execute();

            $valid = $stmt->fetchColumn();

            if( $valid ) {
                $success = true;

                session_start();
                session_regenerate_id();
                $_SESSION['user'] = $_POST['username'];
                session_write_close();
                echo ('CORRECTO');

                exit();
            }

            $con = null;
            return $success;
        }
        catch (PDOException $e) {
            echo $e->getMessage();
            return $success;
        }
    }

Made the below code use prepared statement. 使下面的代码使用编写好的语句。 Your ajax looks fine. 你的ajax看起来不错。 Just the below function that's not. 只是下面的功能不是。

Updated Code: 更新的代码:

   function Login() {
            $success = false;           
            try {
                $con = new PDO( 'mysql:host=localhost;dbname=MY_DB_NAME', 'MY_USRNAME', 'MY_PSW' );
                $sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

                $stmt = $con->prepare( $sql );

                $stmt->execute(array(':username'=>$_POST['username'], ':password'=>$_POST['password']));

                $valid = $stmt->fetchColumn();

                if( $valid ) {
                    $success = true;
                    session_start();
                    session_regenerate_id();
                    $_SESSION['user'] = $_POST['username'];
                    session_write_close();
                    echo ('CORRECTO');
                    exit();
                }

                $con = null;
                return $success;
            }
            catch (PDOException $e) {
                echo $e->getMessage();
                return $success;
            }
        }

 Login();

^ And the function has to be executed for the response to be sent. ^并且必须执行该函数才能发送响应。

I has code of login with php and ajax, i hope understand my example. 我有使用php和ajax登录的代码,我希望理解我的示例。 in you php scrip, you have example: echo 'correcto', when is echo json_encode(array('error' => true , 'mensaje' => "usuario o password incorrectos")); 在您的php脚本中,您有示例:echo'correcto',何时echo json_encode(array('error'=> true,'mensaje'=>“ usuario o password errorsos”)));

for you: 为了你:

echo json_encode(array(message => 'CORRECTO'));

and you script js 和你脚本js

success: function(data) {
  if (data.message == 'CORRECTO') {
    window.location = 'index.php';
  }else{
   // other code
  }
}

Create at script only php, without class name.. only php. 仅在脚本中创建php,没有类名。 and instance you class when you have exist method login.. and in you method login pass parameters 和实例的类,当您已经存在方法登录时..和在您方法登录传递参数

$user = $_POST['username'];
$pass = $_POST['password'];

    <?php

    include_once "conexion.php";

     $user = $_POST['username'];
     $pass = $_POST['password'];
     if($_POST){
       $class = new Class();
        if( $class->login($user,$pass))
          echo json_encode(array(message => 'CORRECTO'));
        else
         echo json_encode(array(message => 'ERROR'));
     }

    ?>

// en your class when function
    function Login($user,$pass) {
            $success = false;           
            try {
                $con = new PDO( 'mysql:host=localhost;dbname=MY_DB_NAME', 'MY_USRNAME', 'MY_PSW' );
                $sql = "SELECT * FROM users WHERE username = ".$user." AND password = ".$pass." LIMIT 1";

                $stmt = $con->prepare( $sql );

                $stmt->execute();

                $valid = $stmt->fetchColumn();

                if( $valid ) {
                    $success = true;
                    session_start();
                    session_regenerate_id();
                    $_SESSION['user'] = $_POST['username'];
                    session_write_close();
                    $success = true;
                    exit();
                }
                $con = null;
                return $success;
            }
            catch (PDOException $e) {
                echo $e->getMessage();
                return false;
            }
        }

I hope help you 希望对你有帮助

Could you do var_dump ($_REQUEST) to see what do you send to the server? 您可以执行var_dump($ _REQUEST)来查看发送到服务器的内容吗?

(I think when you click the submit button the page get refreshed?) (我认为当您单击“提交”按钮时页面会刷新吗?)

Update: 更新:

1- change the submit to a button: 1-将提交更改为按钮:

<input type="button" name="loginsub" id="loginsub" value="Login">

2- Use jQuery to trigger the call: 2-使用jQuery触发呼叫:

$('#loginsub').on('click',function(){
    var data={};
    data['username']=$('#username').val();
    data['password']=$('#password').val();
    //put the ajax call here, and replace $(this)serialize() with data
});

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

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