1

I have the following php code, which works on its own. However, when using it AJAX it returns an empty response.

PHP login code:

<?php
session_start();
include_once  'resources/database.php';

if(isset($_POST['m_login_signin_submit'])) {
    $email = trim($_POST['email']);
    $user_password = trim($_POST['password']);

    $password = MD5($user_password);

    try {
        $stmt = $db->prepare("SELECT * FROM users WHERE email=:email");
        $stmt->execute(array(':email' => $email));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $count = $stmt->rowCount();
            if($row['password']==$password) {
                echo '1';
                $_SESSION['user_session'] = $row['id'];
            } else {
                echo 'You do not matter.';
            }
    } catch (PDOException $ex) {
        echo $ex->getMessage();
    }
}

AJAX Code:

$(document).ready(function () {
/* validation */
$("#login-form").validate({
    submitHandler: submitForm
});
function submitForm() {
    var email = $('#email').val();
    var password = $('#password').val();
    console.log(data);
    $.ajax({
        type: 'POST',
        dataType: 'text',
        url: 'partials/processLogin.php',
        data: {
            email:email,
            password:password
        },
        success: function (response) {
            console.log("Checking success.");
            console.log(response);
        },
        error: function () {
            console.log("error");
        }
    });
    return false;
}

});

In console, all the values pass correctly and it returns success but the value is empty. Any help is greatly appreciated.

Thank you

tuan
  • 11
  • 2
  • 1
    ***You really shouldn't use [MD5 password hashes](http://security.stackexchange.com/questions/19906/is-md5-considered-insecure)*** and you really should use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. Make sure you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Feb 28 '18 at 18:43

1 Answers1

3

You did not pass any m_login_signin_submit in your request, therefore you never go into your main if statement. I'm guessing that is the form's submit button but since this is ajax it will not get sent unless you do it explicitly.

    data: {
        email:email,
        password:password,
        m_login_signin_submit: 1
    },
Musa
  • 96,336
  • 17
  • 118
  • 137
  • Yes, 'm_login_signin_submit ' is the form's submit button. I added your suggestion to my code and still returns as empty. – tuan Feb 28 '18 at 22:25