0

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:

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;
        }
    }
j08691
  • 204,283
  • 31
  • 260
  • 272
opuerma
  • 3
  • 3

3 Answers3

1

Made the below code use prepared statement. Your ajax looks fine. 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.

Karlo Kokkak
  • 3,674
  • 4
  • 18
  • 33
  • Still always getting invalid credentials, i think the problem is that i never enter to the funtion Login, cuz i put an alert in the firt line of the function and it never shows up, should i call it somewhere? because if i delete the "function Login() {" line and the closing bracked im getting a "http 500 error, server internal error" – opuerma Apr 21 '18 at 09:40
  • Yes. You need to call `Login()` function somewhere for your code to work as required. Make sure only the `Login()` function outputs something. – Karlo Kokkak Apr 21 '18 at 09:49
  • PHP code: https://pastebin.com/bXuEB4CE The other code: https://pastebin.com/8vfjAdJN – opuerma Apr 21 '18 at 09:59
  • 1
    Worked! Thanks you! – opuerma Apr 21 '18 at 11:11
  • It also work deleting de "function Login() {" line and the closing bracked, don't know why wasn't working yesterday because i already tried this. Thanks for the help! – opuerma Apr 21 '18 at 11:17
0

I has code of login with php and ajax, i hope understand my example. in you php scrip, you have example: echo 'correcto', when is echo json_encode(array('error' => true , 'mensaje' => "usuario o password incorrectos"));

for you:

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

and you script 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. 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

JuanL
  • 101
  • 3
0

Could you do var_dump ($_REQUEST) to see what do you send to the server?

(I think when you click the submit button the page get refreshed?)

Update:

1- change the submit to a button:

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

2- Use jQuery to trigger the call:

$('#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
});
Med.ZAIRI
  • 154
  • 5