MajorSin
MajorSin

Reputation: 81

Returning True/False from PHP to Ajax

The past day's I've been trying to return a true or false boolean to Ajax.

The Process: Someone submit's a form > Send to a PHP file > From PHP, check everything is correct. If yes, return true and echo 'correct'. > Output the result. In this case, it'll have to echo correct. And check if it's true or false.

The problem is, it will always return a false. Even when everything is correct. So when my login is correct, it will return a correct, as I expect. But it won't return a true.

My form:

<form id="loginform" class="col s12" name="loginform" method="post">
    <div class="input-field col s12">
        <i class="fas fa-user material-icons prefix"></i>
        <input id="hn" type="text" class="validate" name="hn">
        <label for="hn">Gebruikersnaam</label>
    </div>
    <div class="input-field col s12">
        <i class="fas fa-key material-icons prefix"></i>
        <input id="ww" type="password" class="validate" name="ww">
        <label for="ww">Wachtwoord</label>
    </div>
    <button class="mui-btn mui-btn--raised mui-btn--primary" id="forminlog"><i class="fas fa-chevron-right"></i> Inloggen</button>

Ajax:

$("#forminlog").click(function(){
    $.ajax({
        type: 'POST',
        data: {hn: document.getElementById("hn").value, ww: document.getElementById("ww").value},
        url: 'login.php',
        success: function(output) {
            swal(output);
            if(output == true){
                alert("true");
            } else {
                alert("false");
            }
        }
    });
    event.preventDefault()
});

PHP:

<?php
function login(){
    header('Content-Type', 'application/json');
    //VARIABLEN
    $pgebruiker = $_POST['hn'];
    $pww = $_POST['ww'];
    //LEGE VELDEN
    if(empty($pgebruiker) || empty($pww)){
        echo 'Vul alle velden in';

    }
    else {
        //DATA VANUIT DB
        include("connection.php");
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sth = $dbh->prepare("SELECT * FROM gebruikers WHERE gebruikersnaam = :gebruiker");
        $pdoExec = $sth->execute(array(":gebruiker"=>$pgebruiker));
        $sth->execute();
        $result = $sth->fetch(PDO::FETCH_OBJ);
        //GEBRUIKERSNAAM
        $gebruikersnaam = $result->gebruikersnaam;
        //WACHTWOORD
        $wachtwoord =  $result->wachtwoord;
        if(!strcasecmp($pgebruiker, $gebruikersnaam) == 0){
            echo 'Verkeerd gebruikersnaam.';
        }
        elseif(!password_verify($pww, $wachtwoord) /*strcasecmp($pww, $wachtwoord) == 0*/){
            echo 'Verkeerd wachtwoord';
        }
        else{
            echo 'Correcte gegevens.';
            return true;
            /*session_start();
            $_SESSION['gebruiker'] = $gebruikersnaam;
            header('Location: veilig.php');*/
            //exit;
        }
    }
}
login();
?>

Upvotes: 1

Views: 1553

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

Two thing are to be returned from your login() function:

  • a message
  • a boolean

So I suggest you to output the data as a json string like this:

Before the login() function, declare an array:

$response = [];

Then, within all the conditions you have... just set msg and success accordingly, like, for example if the login is correct:

$response["msg"] = "You're logged in buddy!";
$response["success"] = true;

At the end of all conditions echo the array as a json string:

echo json_encode($response);

It will send the following string:

{"msg":"You're logged in buddy!","success":true}

** Make sure that echo is the only echo in that PHP file!

On client-side now, in the success callback, it would be:

success: function(output) {

        // Parse the string.
        var json = JSON.parse(output);

        swal(json.msg); // Sweet Alert...
        if(json.success){
            // something to do with the boolean true
        } else {
            // Something else
        }
    }

Upvotes: 2

Related Questions