简体   繁体   English

带有ajax的php-mysql登录系统

[英]php-mysql login system with ajax

I started learning php lately so i'm not so good with it. 我最近开始学习php,所以我不太满意。 I've been trying to create a login system with php/ajax. 我一直在尝试用php / ajax创建一个登录系统。 I've tried all i could but can seem to figure out where the actual problem is coming from. 我已经尽力了,但是似乎可以弄清楚实际问题是从哪里来的。 Ajax couldn't get the data from my process.php file even though i already added it in the url. 即使我已经在URL中添加了Ajax,也无法从我的process.php文件中获取数据。 The only codes that get executed are those from the index script but nothing from process. 唯一执行的代码是来自索引脚本的代码,而没有来自进程的代码。 My database connection is ok. 我的数据库连接正常。 Just that there seem to be no communication between ajax and process.php. 只是ajax和process.php之间似乎没有通信。 It just executes the 'else'(data==true) code in Ajax instead. 它只是在Ajax中执行'else'(data == true)代码。 I'm sorry i may not be able to express myself very well but i just hope you understand what i mean. 对不起,我可能无法很好地表达自己,但我只希望您理解我的意思。 Below are the files i created. 以下是我创建的文件。

here is the member.php class 这是member.php类

       <?php
        class member {

       public $table;
       public function __construct(){

       $this->table = "users";   


         }


       //login check
      public function check($username,$password,$conn){

       $this->table = "users";
       //$password_hash = md5($password);

       $stmt = $conn->prepare("SELECT * FROM ".$this->table." WHERE 
       Username='$username' AND Password='$password' LIMIT 1");
       $stmt->execute();
                    if($stmt->rowCount() > 0)
                    {

                      while($row = $stmt->fetch(PDO::FETCH_ASSOC))
                      {
                            // print_r($row);
                                 $_SESSION['id'] = $row['id'];
                                 ;
                                 $_SESSION['email'] = $row['email'];

                                 return true;
                      }
                    } else {
                         return false; 

                   }

      }


     }

    ?>

here is the process.php file 这是process.php文件

    <?php
     session_start();

    require_once('member.php');

   //for login
   if(isset($_POST['login'])){
   $username = $_POST['username'];
   $password = $_POST['password'];


   if($username ==""){
    echo "Please enter your email";
   }
   elseif($password == ""){
    echo "Please enter your password";
   }
   else{

    //connect to database
        require_once('db.php');

        //instantiate the member class
        $member = new member();

        $login_check = $member->check($username,$password,$conn);
        if($login_check == true){
            echo true;

        }
        else{
            echo "Invalid email or password";
          }
         }

         }

            ?>

and here is the index file that contains the ajax code 这是包含ajax代码的索引文件

    <?php
     //session_start();
     include('header.php');
     require_once('db.php');
     require('process.php'); 


    ?>
   <html lang="en">
   <head>
    <title>Login/Signup</title>

 </head>
 <body>
    <div class="container">
            <div class="content">
            <div class="form">
                <div id = "message"></div>
                <ul class="tab">
                    <li><a href="">LOGIN</a></li>
                    <li><a href="">SIGNUP</a></li>
                </ul>
                <div class="tab-content">
                    <div class="login-tab">
                        <form   id="login_form" method="post" class="login- 
 form"  >
                            <div class="">
                                <input type="text" id = "username" 
 name="username" class="form-control" placeholder="Enter your Username">
                            </div>
                            <div class="">
                                <input type = "password" id = "password" 
 name="password" class="form-control" placeholder="Enter your Password">
                            </div>
                            <div><button type = "submit" id = "login" 
 name="login" class="btn btn-primary" >login</button></div>
                        </form>
                        <div class="clearfix"></div>
                        <p>Or Login with</p>
                        <ul class="alt-login">
                            <li><a href=""><img src=""></a></li>
                            <li><a href=""><img src=""></a></li>
                            <li><a href=""><img src=""></a></li>
                        </ul>
                    </div>
                    <div class="clearfix"></div>
                    <div class="tab_signup">
                        <form>

                        </form>
                    </div>

                </div>
            </div>
        </div>
    </div>
  </body>


  <script type="text/javascript">
    $( document ).ready(function() {
  $("#login").click(function(e){
    e.preventDefault();


    var username = $("#username").val();

    var password = $("#password").val();



         var data = $("login_form").serialize();



         $.ajax({
        type : "POST",
        url: 'process.php',
        data : data,
        success: function(data){

         if(data==true){
            $("#message").addClass('alert alert-success');
        $("#message").html("Login successful");

        $("#login").html('Redirecting..');

        window.location ="dashboard.php";
         }  
         else{
            //alert(data);
            $("#message").addClass('alert alert-danger');

            $("#message").html('login failed');
             $("#login").html('Failed');
         } 


        },
       error : function(jqXHR,textStatus,errorThrown){
             if(textStatus ='error'){
                alert('Request not completed');
             }
            $("#login").html('Failed');
        },
        beforeSend :function(){

        $("#message").removeClass('alert alert-danger');
        $("#message").html('');

        $("#login").html('Logging in..');
        },
     });


    // }

    });



   });
  </script>
  </html>   

PS i'm not bothering about hashing the password now cos i'm still test. 附言:我现在不担心哈希密码,因为我仍在测试中。

You are passing data using GET method in Ajax but using POST when retrieving data in process.php file. 您正在Ajax中使用GET方法传递数据,而在process.php文件中检索数据时则使用POST You need to change ajax calling code and should use post method. 您需要更改ajax调用代码,并应使用post方法。 Also serialize function doesn't append login input element which you need to push manually. 此外, serialize功能不会附加您需要手动推送的登录输入元素。 I have updated code and it will be like below: 我已经更新了代码,它将如下所示:

            $("#login").click(function (e) {
                e.preventDefault();
                var data = $("#login_form").serializeArray();
                data.push({ name: this.name, value: this.id });
                console.log(data);
                $.ajax({
                    type: "POST",
                    url: 'process.php',
                    data: data,
                    success: function (data) {
                        if (data == true) {
                            $("#message").addClass('alert alert-success');
                            $("#message").html("Login successful");
                            $("#login").html('Redirecting..');
                            window.location = "dashboard.php";
                        } else {
                            $("#message").addClass('alert alert-danger');
                            $("#message").html('login failed');
                            $("#login").html('Failed');
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        if (textStatus = 'error') {
                            alert('Request not completed');
                        }
                        $("#login").html('Failed');
                    },
                    beforeSend: function () {

                        $("#message").removeClass('alert alert-danger');
                        $("#message").html('');

                        $("#login").html('Logging in..');
                    },
                });
            });

You can update your code as it is and it should work fine. 您可以按原样更新代码,它应该可以正常工作。 Hope it helps you. 希望对您有帮助。

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

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