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

7
  • console.log(data)? and what does the console's network tab show? Commented Mar 17, 2019 at 18:37
  • Youre using prepared statements incorrectly. Parameterize Commented Mar 17, 2019 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() and password_verify() 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. Commented Mar 17, 2019 at 19:54
  • 2
    Also, your code is wide open to SQL injection. Don't build queries by sticking strings together. Instead, use prepared statements with parameter binding. Both this comment and my previous one are of paramount importance. Don't ignore them. Commented Mar 17, 2019 at 19:54
  • Possible duplicate of How can I store my users' passwords safely? Commented Mar 17, 2019 at 19:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 I have updated my answer. Please check this and it should work fine.
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.
Connect with me over Skype: rohit.mittal54. Let me debug your code
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 zoom.us/j/5544252963

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.