-1

I started learning php lately so i'm not so good with it. I've been trying to create a login system with 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. 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. It just executes the 'else'(data==true) code in Ajax instead. 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

       <?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

    <?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

    <?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>   

P.S i'm not bothering about hashing the password now cos i'm still test.

epospiky
  • 11
  • 5
  • `console.log(data)`? and what does the console's network tab show? – Sindhara Mar 17 '19 at 18:37
  • Youre using prepared statements incorrectly. Parameterize – user3783243 Mar 17 '19 at 18:42
  • 2
    Whatever tutorial you're following for the PHP login stuff is hopelessly outdated and insecure. You should _**never**_ store plaintext passwords, and the commented out code to hash passwords with MD5 is also _amazingly insecure_. Find a new one that uses [`password_hash()`](https://secure.php.net/manual/en/function.password-hash.php) and [`password_verify()`](https://secure.php.net/manual/en/function.password-verify.php) and follow that instead. There's no excuse for storing plaintext passwords (or using MD5), regardless of whether you're "just testing" or not. Learn to do this correctly now. – ChrisGPT was on strike Mar 17 '19 at 19:54
  • 2
    Also, your code is _**wide open** to [SQL injection](https://en.wikipedia.org/wiki/SQL_injection)_. Don't build queries by sticking strings together. Instead, use [prepared statements](http://php.net/manual/en/pdo.prepare.php) with [parameter binding](http://php.net/manual/en/pdostatement.bindparam.php). Both this comment and my previous one are of **paramount importance**. Don't ignore them. – ChrisGPT was on strike Mar 17 '19 at 19:54
  • Possible duplicate of [How can I store my users' passwords safely?](https://stackoverflow.com/questions/1581610/how-can-i-store-my-users-passwords-safely) – ChrisGPT was on strike Mar 17 '19 at 19:58
  • Thanks @Chris for the tips. I'll look into that – epospiky Mar 17 '19 at 21:20
  • @kuh-chan. It seems it's getting the data from process.php but not entirely. I did console.log(data) and it show invalid email or password when the details are wrong. But when the details are correct it just remains as it is. – epospiky Mar 17 '19 at 21:35

1 Answers1

2

You are passing data using GET method in Ajax but using POST when retrieving data in process.php file. You need to change ajax calling code and should use post method. Also serialize function doesn't append login input element which you need to push manually. 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.

Rohit Mittal
  • 2,064
  • 2
  • 8
  • 18
  • Did that but still. I actually wanted to trying out something hence the get method. I just forgot to edit before posting it here. – epospiky Mar 17 '19 at 20:59
  • @epospiky I have updated my answer. Please check this and it should work fine. – Rohit Mittal Mar 18 '19 at 05:14
  • Thanks very much for your reply. I updated the code just like you posted but nothing changed. It is still giving out the 'login failed' message. I really have no idea why. – epospiky Mar 18 '19 at 06:10
  • Connect with me over Skype: rohit.mittal54. Let me debug your code – Rohit Mittal Mar 18 '19 at 06:12
  • Hi @Rohit Mittal. Thanks again for your reply. I actually don't have Skype credit right now perhaps we can try other means say zoom. You can hit it here https://zoom.us/j/5544252963 – epospiky Mar 18 '19 at 11:04