I am trying to login via html and php using Ajax and JQuery.
I have managed to do:
The user enters the data and through jQuery and Ajax calls a php script that checks the data in the database.
What I would like to do is:
If the username and/or password are not correct, show a hidden element in my index.php with the error message.
Index code:
<?php
session_start();
// Checking the session
if(isset($_SESSION['userSession'])){
if(!empty($_SESSION['userSession'])){
header("Location: models/userPanel.php");
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<!-- CSS imports -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/main.css" />
<!-- JQuery include -->
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<!-- <script type="text/javascript" src="js/loginForm.js"></script> -->
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<!-- Navigation Bar content -->
<nav class="navBar">
<ul>
<li><a class="hover" href="index.php">Index</a></li>
</ul>
</nav>
<!-- Body content -->
<div class="bodyContainer">
<!-- Form -->
<div class="formContainer">
<p class="formTitle">Login form</p>
<form id="loginForm" method="post">
<div class="formDataContainer">
<div id="error"><!-- Error will be shown here ! --></div>
<label for="userMail"><span class="labelText">Email</span></label>
<input type="email" placeholder="Enter Username" name="userMail" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
<label for="psw"><span class="labelText">Password</span></label>
<input type="password" placeholder="Enter Password" name="psw" required autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
<button type="submit" id="btnLogin" name="btnLogin">Sing in</button>
<button type="button" id="registerBtn" onclick="location.href='models/registerForm.php';">Register</button>
</div>
</form>
</div>
</div>
<script>
$('form[id=\'loginForm\']').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'POST', url: 'php/loginProcess.php', data: data, beforeSend: function(){
$('#error').fadeOut();
$('#btnLogin').html('Sending ...');
}, success: function(response){
if (response == 'ok'){
$('#btnLogin').html('Signing In ...');
setTimeout(' window.location.href = "home.php"; ', 4000);
}
else
{
$('#error').fadeIn(1000, function(){
$('#error').html(response);
$('#btnLogin').html('Sign In');
});
}
},
});
return false;
});
/* login submit */
</script>
</body>
</html>
LoginProcess.php file code
<?php
session_start();
print_r($_POST);
require_once 'dbConfig.php';
$query = "SELECT idUser, name, surname, mail, level
FROM users
WHERE mail = ? AND password = ?";
// TODO recoger datos
if(isset($_POST["userMail"]) && isset($_POST["psw"])){
if(!empty($_POST["userMail"]) && !empty($_POST["psw"])){
// TODO comprobamos la base de datos
// Clean obtained data
$userName = $mysqli->real_escape_string(trim($_POST["userMail"]));
$passwd = $mysqli->real_escape_string(trim($_POST["psw"]));
// Crypt the Password
$password = md5($passwd);
print_r($password);
// Attempt to prepare the query
if($stmt = $mysqli->prepare($query)){
if($stmt->bind_param("ss", $userName, $password)){
$stmt->execute();
// Obtain the result
$result = $stmt->get_result();
// If there is no result, we will show an error message
if($result->num_rows === 0){
echo "<script>
$('#error').fadeIn(3000, function(){
$('#error').html(Invalid username or password);
$('#btnLogin').html('Sign In');
});
</script>";
}else{
$row = $result->fetch_array();
print_r($row);
}
$mysqli->close();
}else{
// TODO handle error
}
}
}
}
?>
How could I call the element from the index? I'm trying to do an echo with a script but it doesn't seem to work.
Thanks for everything.
You have pretty much everything set up now, including the Javascript handler for what to do with
<div id="error"></div>
when you get the error. But what seems to me that it won't work is printing inloginProcess.php
the Javascript code. Instead, you should just return the text message, since in your own Javascript you already have the same code, and in general, it should handle the behavior in HTML.That is, what you already put in the
loginProcess.php
change it for:And as for your hidden element in the index.php, because with the same Javascript you would have to hide it and show it, as appropriate.
Using JQuery:
EDITED:
As a suggestion of where and when to "hide" your
<div>
error, it would be first when you start the script and second when you submit the form: In your index code, I would place it in this sector:The idea is that (1) it is hidden from the eyes of the web user the first time he enters, and (2) it is hidden again every time you submit the form (for the cases in which it was visible after making a previous failed login attempt; if the user does not fail to login, the message does not appear again).