I have a login form, which has to be executed through ajax to PHP. From PHP he has to send a message back to ajax, and Ajax has to display the message. The problem is, that some of the messages doesn't display. It'll give the following error:
Conditional Statements:
As I said, some statements does work and some doesn't
- Check if form is empty. This doesn't work. What I've tried: I opened the
login.php
via URL. So, the form was empty. It returned:{"msg":"formleeg"}
as it has to be. But still, it doesn't work. - If the form isn't empty: Check if the username is correct. This doesn't work.
- Check if the password is correct. This works correctly.
- Last statement, the
else
works perfect.
My Codes:
The 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>
</form>
Ajax:
$("#forminlog").click(function(){
$.ajax({
type: 'POST',
data: {hn: document.getElementById("hn").value, ww: document.getElementById("ww").value},
url: 'login.php',
success: function(antwoordform) {
var jsonverzoek = JSON.parse(antwoordform);
if(jsonverzoek.msg == "formleeg"){
swal("Lege form")
}
else if(jsonverzoek.success == true){
swal("Everything OK");
}
else {
swal("false");
}
}
});
event.preventDefault()
});
PHP:
<?php
$resultaat = [];
function login(){
//VARIABLEN
$pgebruiker = $_POST['hn'];
$pww = $_POST['ww'];
//LEGE VELDEN
if(empty($pgebruiker) || empty($pww)){
echo 'Vul alle velden in';
$resultaat["msg"] = "formleeg";
}
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){
$resultaat["success"] = false;
}
elseif(!password_verify($pww, $wachtwoord) /*strcasecmp($pww, $wachtwoord) == 0*/){
$resultaat["success"] = false;
}
else{
$resultaat["success"] = true;
/*session_start();
$_SESSION['gebruiker'] = $gebruikersnaam;
header('Location: veilig.php');*/
//exit;
}
}
echo json_encode($resultaat);
}
login();
?>