0

I have a simple code here that uses json_encode and echo out the response in PHP. Here is my code:

app.js

$scope.login = function() {
        var data = {
            username: $scope.login.username,
            password: $scope.login.password
        };

        $http.post('endpoints/login.php', data)
        .success(function(response) {
            if(response.success == "true") {
                alert('nice');
            } else {
                alert('not nice');
            }
        })
        .error(function(response) {
            console.log(response);
        });

    };

login.php

$data = json_decode(file_get_contents("php://input"));
$stmt = $db->prepare('SELECT * FROM accounts WHERE username=? AND password=?');
$stmt->execute(array($data->username, $data->password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0)
{
    $response = [
        "success" => true
    ];

    echo json_encode($response);
}
else
{
    $response = [
        "success" => false
    ];

    echo json_encode($response);
}

It works perfectly but this part doesn't work:

if(response.success == "true") {
  alert('nice');
} else {
  alert('not nice');
}

When I add console.log(response) I get Object {success: true} or Object {success: false}.

Am I missing something here? Thank you.

7
  • console.log(response) and your answer might become clear. Commented Sep 28, 2015 at 15:35
  • @KevinB I get true or false, it works properly but I can't make the if statement work Commented Sep 28, 2015 at 15:38
  • I expected response to have a data property. Commented Sep 28, 2015 at 15:39
  • 1
    When you use success(), the data itself is passed in. FYI, success() is being deprecated, so you should use normal promise methods, such as then() Commented Sep 28, 2015 at 15:42
  • 1
    Ah, that's it. I never use .success, so didn't notice. :) Commented Sep 28, 2015 at 15:43

1 Answer 1

2

You need to use a boolean in your if statement, not a string because true != "true". Change your if statement to the following:

if(response.success === true) {
Sign up to request clarification or add additional context in comments.

1 Comment

There you go. I did this but instead I used "true" which makes it not working also. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.