For practice I'm making login form with only one user (no database) and now I have a problem because I don't know how to get error messages from JSON with AJAX to display in results (i see them in firebug). I don't know where is mistake. Here is my scriptLogin.php code:
<?php
const USERNAME = 'user1';
const EMAIL = 'me@me.me';
const PASSWORD = 'pass1';
if (!empty($_POST)) {
$username = null;
$email = null;
$password = null;
if (isset($_POST['contactUser'])) {
$username = (string)$_POST['contactUser'];
}
if (isset($_POST['contactPass'])) {
$password = (string)$_POST['contactPass'];
}
if (isset($_POST['contactEmail'])) {
$email = (string)$_POST['contactEmail'];
}
$errMessage = [];
if ($username != USERNAME || $email != EMAIL || $password != PASSWORD ) {
$errMessage['contactInput'] = 'Please enter valid user,mail and pass!';
}
if (empty($username)) {
$errMessage ['contactUser'] = 'Please enter a username!';
}
if (empty($email)) {
$errMessage ['contactEmail'] = 'Please enter your E-Mail!';
}
if (empty($password)) {
$errMessage ['contactPass'] = 'Please enter a password!';
}
if (!empty($errMessage)) {
http_response_code(400);
} else {
http_response_code(200);
}
header('Content-Type: application/json');
echo json_encode($errMessage);
exit();
}?>
and here is my login.html code
<div id="result"></div>
<form method="post" action="loginScript.php" id="myForm" >
<input type="text" name="contactUser" id="username" placeholder="Username" />
<input type="text" name="contactEmail" id="email" placeholder="Email" />
<input type="password" name="contactPass" id="password" placeholder="Password" />
<input type="submit" id="btnLogin" value="Login" />
</form>
and here is my AJAX code
$(document).ready(function() {
$('#myForm').submit(function(){
$.ajax({
type: "POST",
url: "loginScript.php",
dataType:'json',
data: $('#myForm').serialize(),
success: function (data) {
$("#result").html("Success - LogIn !");
},
error: function(){
$.getJSON("loginScript.php",
function(json)
{
var output = json.contactInput;
output += json.contactUser;
output += json.contactEmail;
output += json.contactPass;
$("#result").html(output);
}
)
}
});
return false;
});
});
Try:
$("#result").html(JSON.stringify(output));