2

I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.

I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake

From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows

Ajax:

$("#checkLogIn").click(function()
{

    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: rootURL + '/logIn/',
        dataType: "json",
        data: checkLogIn(),
    })
        .done(function(data)
        {
            if(data == false)
            {
                alert("failure");
            }
            else
            {
                alert("Success");
                $.mobile.changePage("#page");
            }
        })
        .always(function(){})
        .fail(function(){alert("Error");});
});

function checkLogIn()
{       
    alert();
    return JSON.stringify({
        "userName": $("#enterUser").val(),
        "password": $("#enterPass").val(),
    });
}

I'll also include the PHP but the PHP works 100% after testing it.

PHP:

$app->post('/logIn/', 'logIn');
function logIn()
{
    //global $hashedPassword;

    $request = \Slim\Slim::getInstance()->request();
    $q = json_decode($request->getBody());
    //$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);


    $sql = "SELECT * FROM users where userName=:userName AND password=:password";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);         
        $stmt->bindParam("userName", $q->userName);
        $stmt->bindParam("password", $q->password);
        $stmt->execute();
        //$row=$stmt->fetch(PDO::FETCH_ASSOC);
        //$verify = password_verify($q->password, $row['password']);

        $db = null;
        //if($verify == true)
        //{
        //  echo "Password is correct";
        //}
        //else
        //  echo "Password is incorrect";

    echo "Success";

    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

I have commented out any and all hashing until I can get this working properly

John
  • 115
  • 10

1 Answers1

1

There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.

So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.

$app->post ( '/logIn/', 'logIn' );
function logIn() {
    global $hashedPassword;
    $request = \Slim\Slim::getInstance ()->request ();
    $q = json_decode ( $request->getBody () );
    $hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);

    $sql = "SELECT * FROM users where userName=:userName";
    try {
        $db = getConnection ();
        $stmt = $db->prepare ( $sql );
        $stmt->bindParam ( "userName", $q->userName );
        $stmt->execute ();
        $row=$stmt->fetch(PDO::FETCH_ASSOC);
        $verify = false;
        if(isset($row['password']) && !empty($row['password']))
            $verify = password_verify($hashedPassword, $row['password']);

        $db = null;
        $response = array();
        $success = false;
        if($verify == true)
        {
            $success = true;
            $response[] = "Password is correct";
        }
        else
        {
            $success = false;
            $response[] = "Password is incorect";
        }

        echo json_encode(array("success"=>$success,"response"=>$response));
    } catch ( PDOException $e ) {
        echo $e->getMessage ();
    }
}

And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.

$("document").ready(function(){
    $("#checkLogIn").click(function()
    {
        var post_data = JSON.stringify({
            "userName": $("#enterUser").val(),
            "password": $("#enterPass").val(),
        });
        $.ajax({
            type: 'POST',
            contentType: 'application/json',
            url: rootURL + '/logIn/',
            dataType: "json",
            data: post_data,
        })
        .done(function(data)
        {
            // data will contain the echoed json_encoded Object. To access that you need to use data.success.
            // So it will contain true or false. Based on that you'll write your rest of the code.
            if(data.success == false)
            {
                var response = "";
                $.each(data.response, function(index, value){
                    response += value;
                });
                alert("Success:"+response);
            }
            else
            {
                var response = "";
                $.each(data.response, function(index, value){
                    response += value;
                });
                alert("Failed:"+response);
                $.mobile.changePage("#page");
            }
        })
        .always(function(){})
        .fail(function(){alert("Error");});
    });
});

Hope it helps.

Community
  • 1
  • 1
Mahendran Sakkarai
  • 8,381
  • 6
  • 44
  • 66
  • Yeah, I changed that just before reading this. I thought there was no way an echo could screw it up. It was originally set to json_encode and I changed it while commenting out the hash and verify to test. Thanks for the help, I was looking back and fourth between this and the code that was working and had no idea why this one didn't work. – John May 26 '15 at 06:38
  • Are there any changes I need to make to the Ajax for hashed passwords? I just tried it with a username and hashed password and it failed. It works with non hashed passwords – John May 26 '15 at 06:47
  • you are comparing the typed password and hashed password in php. So you don't need to do anything in ajax. and in php you no need to select fields from db using username and password. because you ll store the hashed password in db. but you used select with the password you sent from the form. it's different from the hashed password. so you'll get empty row only. so, first select the row with the username and compare the password using the hashed password. i updated the answer.. – Mahendran Sakkarai May 26 '15 at 12:45
  • Doesn't accept the password as the correct password – John May 26 '15 at 13:17