setting up ajax validation response - php

My PHP code for a login form [this part located at the very top on my index.php where I have the login form] looks something like this:
if(isset($_POST['submit'])){
if (!isset($_POST['username'])) $error[] = "Please fill out all fields";
if (!isset($_POST['password'])) $error[] = "Please fill out all fields";
$username = $_POST['username'];
if ( $user->isValidUsername($username)){
if (!isset($_POST['password'])){
$error[] = 'A password must be entered';
}
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: welcome.php');
exit;
} else {
$error[] = '<div style = "text-align:center">Wrong username/password or your account have not been activated </span>';
}
}else{
$error[] = '<div style = "text-align:center">Username required</span>';
}
and the HTML for the login form is like this:
<form role="form" method="post" action="" >
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Your account is now active you may now log in.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Please check your inbox for a reset link.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Password changed, you may now login.</h2>";
break;
}
}
?>
<div class="form-group">
<p align="center">
<font face="Tahoma">Username:</font><font color="#FFFFFF">
</font>
<input type="text" name="username" id="username" class="form-control input-lg" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="1">
</div>
<br>
<div class="form-group">
<p align="center">
<font face="Tahoma">Password: </font><font color="#FFFFFF">
</font><input type="password" name="password" id="password" class="form-control input-lg" tabindex="3">
</div>
<br>
<div align="center">
<input type="submit" name="submit" value="Login" class="btn1" tabindex="5">
</div>
</form>
Now, as this form in submitted if there are ERRORS , it will refresh the whole page and back with error messages on right on top of the form fields. How would I be able to use AJAX / jQuery response to validate for ERRORS without refreshing the whole page. ONLY of there are ERRORS I want it pop the error messages without refreshing. And if it's SUCCESS, then it would log the user in. Can someone help me with this ?
I also have a errors.php file that has only this code in it:
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
I get the concept behind setting up the AJAX method, but IDK how to use it on this code and form. Hope you guys can help.

This is a very broad question with many possible answers, but here's one way to do it.
1. Post your login with AJAX
$.post("loginScript.php", {
username: "username goes here",
password: "password goes here"
}, function(data){
});
2. Echo your results
Your login script should echo out a JSON response that indicates whether the login was successful and if not, what the errors were.
<?php
if(//login conditions)
{
echo json_encode(array(
"success" => true
));
}
else
{
echo json_encode(array(
"success" => false,
"errors" => $errors
));
}
3. Handle the response
$.post("loginScript.php", {
username: "username goes here",
password: "password goes here"
}, function(data){
var json = JSON.parse(data);
if(json.success)
{
//Login was successful
}
else
{
var errors = json.errors;
//Display errors on your page.
}
});

Related

serverside validation for a sign in form

<form method="POST" onsubmit=" return formSubmit() " action="log-it-reports.php">
<div class="userimage">
<img class="userlogo" src="image/userlogo.png" alt="Picture- User Profile picture">
</div><br>
<div class="error" id= "errorMsg"></div><br>
<div class="error" id= "errorMsg1"></div>
<div class="field">
<label class="stafflabel"> Staff Name </label>
<input class="area" placeholder="staffmember or admin" onclick=" return userValidation()" onchange=" return userValidation()" id="staff" name="staffname" type="text" value="<?php echo $staffname;?>" >
</div> <br>
<div class="error" id= "errorMsg2"></div>
<div class="field">
<label class="passlabel"> Password </label>
<input class="area" placeholder="password" onclick=" return userValidation()" onchange=" return userValidation()" id="pass" name="password" type="password" value="<?php echo $password;?>" >
</div><br>
<div class="checkbox">
<input type="checkbox" class="remember-me">
<label class="remember" for="remember-me">Remember me </label>
<a class="pass-link" href="#"> Forgot password?</a>
</div><br><br><br>
<div class="field">
<input class="btn" type="submit" value="Sign in">
</div> <br>
<div class="account-link">
Didn't create an account yet? Create Account
</div>
</form>
I would like to validate a sign in form with predefined usernames (admin, staffmember) and passwords (heretohelp!456 , letmein!123) in the serverside using php, my approach to it is using if statements to check for the posted input , firstly, is this a good approach or there is a better way to do it ? secondly, i'm getting an error in my code that says : syntax error, unexpected 'else' (T_ELSE)
the brackets i have seem to match, the error shows in lines : 15, 32 of this snippet
<?php
$staffname = $_POST['staff'];
$password = $_POST['pass'];
$error = "";
// validating staff member:
if (isset($_POST['submit'])) {
if ($staffname == "staffmember") {
if ($password == "letmein!123") {
$error = "" ;
}
// redirect to the logs report page when successful
header("location: log-it-reports.php");
else {
$error = "* You have entered a wrong password!";
}
}
else {
$error = "You have entered a wrong staff name!";
}
}
// validating admin:
if (isset($_POST['submit'])) {
if ($staffname == "admin") {
if ($password == "heretohelp!456") {
$error = "" ;
}
// redirect to the logs report page when successful
header("location: update-log-reports.php");
else {
$error = "* You have entered a wrong password!";
}
}
else {
$error = "You have entered a wrong staff name!";
}
}
?>
I have fixed your code, so at least it is somewhat DRY and solves your syntax issues as pointed out by people in the comments.
Any decent PHP editor (use Vscode with the inteliphense plugin if you need something free) will show you syntax errors when you code and help you with PHP syntax. If you do use it, make sure you read the instructions and disable the default php plugins as per it's instructions.
<?php
// validating staff member:
$staffname = $_POST['staff'] ?? '';
$password = $_POST['pass'] ?? '';
$error = "";
if (isset($_POST['submit'])) {
if ($staffname == "staffmember") {
if ($password == "letmein!123") {
// redirect to the logs report page when successful
header("location: log-it-reports.php");
exit;
} else {
$error = "* You have entered a wrong password!";
}
} else if ($staffname == "admin") {
if ($password == "heretohelp!456") {
// redirect to the logs report page when successful
header("location: update-log-reports.php");
exit;
} else {
$error = "* You have entered a wrong password!";
}
} else {
$error = "You have entered a wrong staff name!";
}
// Maybe you want to actually send the error back to the browser if there was one?
echo "<p>$error</p>";
}
Pro tip: Your scripts should omit the php end tag ie. ?>. You never need it at the end of any PHP script, and having it included scripts can create output when you don't want or expect it. You only need to use the end tag when you have a script that has a mixture of PHP and html, and you are going in and out of PHP blocks. If PHP is the last thing in a script, then leave off the ?>
Something I added for your $_POST assignments: The Null coalescing operator. This handles the problem of someone submitting your form but leaving off either of the required fields.

Bootstrap alert with login form

I can't understand how can I show a bootstrap alert whenever a user successfully logs in, I've tried it but it is already showing the success or fail message and also it is showing undefined index of $_SESSION['user_id'] which is id in my database.
</div></header>
<section class="clear" id="login-form"><center>
<h1 style="font-size: 30px;">Login</h1><br>
<?php
if ($_SESSION[''] == false) {
echo '<center><div class="alert alert-success">Login Successful!!</div></center>';
}
else{
echo '<center><div class="alert alert-warning">Login Error!!</div></center>';
}
?>
<form action="includes/login.inc.php" method="POST">
<input type="text" name="username" placeholder="Username/E-mail" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button name="submit">Login</button>
</form></center></section>
</body>
First you need to check the user_in from $_SESSION weather it is exist or not. If you set session after authentication, you can use the following:
if (isset($_SESSION['user_id']) && $_SESSION['user_id']) {
echo '<center><div class="alert alert-success">Login Successful!!</div></center>';
} else {
echo '<center><div class="alert alert-warning">Login Error!!</div></center>';
}
Use isset: whatever you set for the user during successful login in the session
<?php
if (isset($_SESSION['user_id'])) {
echo '<center><div class="alert alert-success">Login Successfull!!</div></center>';
}
else{
echo '<center><div class="alert alert-warning">Login Error!!</div></center>';
}
?>

Undefined variable while retrieving variable from action form scripts

<?php
if($_POST) {
//not empty
//atleast 6 characters long
$errors = array();
//start validation
if(empty($_POST['email'])) {
$errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;'>Please write down your email!</p>";
}
//check errors
if(count($errors) == 0) {
//redirect to success pages
header("Location: success.php");
exit();
}
}
?>
<form action="" method="POST" class="searchform" dir="ltr">
<input type="text" name="email" placeholder="Your email address"/>
<button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
<p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
<?php if(count($errors) == 0){
echo "<p id='para' dir='rtl'>
You can add your email to get the latest updates.</p>";
} ?>
</form>
I want to show the paragraph with id='para' (line 31) when the form is not submitted yet and if the user clicked on submit button without entering his email address ,the error message will pop up and that paragraph will not be shown anymore.. To do this I set the if(count($errors) == 0) but I get the Undefined variable error message on line 31. Maybe because I can not take a variable from action scripts until the form is not submitted. Any solution to my problem please?
Try this code:-
<?php
$errors = array();
if($_POST)
{
//not empty
//atleast 6 characters long
//start validation
if(empty($_POST['email']))
{
$errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;'>Please write down your email!</p>";
}
//check errors
if(count($errors) == 0)
{
//redirect to success pages
header("Location: success.php");
exit();
}
}
?>
<form action="" method="POST" class="searchform" dir="ltr">
<input type="text" name="email" placeholder="Your email address"/>
<button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
<p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
<?php if(count($errors) == 0){echo "<p id='para' dir='rtl'>You can add your email to get the latest updates.</p>";}?>
</form>
The problem is that your <form> is outside the if($_POST), so it will be shown whether or not $_POST was set. But $errors is only set inside the if. There are two simple ways to fix this:
Move the initialization of $errors to before the if.
Use if(empty($errors) instead of if(count($errors) == 0). empty() doesn't complain if the variable isn't set.

How to replace die() statement?

if(!empty($_POST))
{
if(empty($_POST['username'])) {die("Please enter a username.");}
....
Result is blank page - with the above alert.
I want to keep the form on the page. Something like:
if(empty($_POST['username']))?> <div id="info"><?php{echo "Please enter a username"};?></div>
So, just write an info, and stop the code execution from this point.
To Stop execution but you can use:
die( ' <div id="info">Please enter a username</div> ');
To allow the rest of the page to load you can use:
$errors = array();
if(empty($_POST['username'])) {
$errors[] = 'Please enter your username';
}
Then later in your html you can add
foreach($errors as $error){
echo "<div class='error'>$error</div>;
}
Rather than "stopping execution" on a single validation error, get all the errors and display them to the user:
<?php
if (!empty($_POST))
{
// validate form
$errors = array();
if (empty($_POST['username']))
{
$errors['username'] = 'Please enter a username.';
}
if (empty($_POST['address']))
{
$errors['address'] = 'Please enter an address.';
}
if (empty($errors))
{
// save to database then redirect
}
}
?>
<form>
Username:<br />
<input type="text" name="username" value="" /><br />
<?php if (!empty($errors['username'])): ?>
<div class="error">
<?php echo $errors['username'] ?>
</div>
<?php endif ?>
Address:<br />
<input type="text" name="address" value="" /><br />
<?php if (!empty($errors['address'])): ?>
<div class="error">
<?php echo $errors['address'] ?>
</div>
<?php endif ?>
</form>
Set some flag and returns/redirects to the same page. On the same page (script with form), check for the flag set and display the message.

How do I validate forms and present error messages using PHP?

Let's say we have this form:
<form action="submit.php" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="Submit" value="Login" />
</form>
How do I validate this form using submit.php, and how do I present an error message if it doesn't pass validation? With Javascript validation I would just change the innerHTML of some element to the error message, but this is not possible with PHP. As you can see I'm a total newbie, so please help me out.
In ugly form:
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$pw = $_POST['password'];
if (empty($username)) {
$errors[] = "Please enter your username";
}
if (empty($pw)) {
$errors[] = "Please provide your password";
}
if (!canLogin($username, $pw)) {
$errors[] = "Invalid login. Try again";
}
if (count($errors) == 0) {
... login is ok, go do something else
}
}
# Display error conditions, if there are any
if (count($errors) > 0) {
echo "<p>The following errors must be corrected:</p><ul><li>";
echo implode("</li><li>", $errors);
echo "</ul>";
}
?>
<form ...>
<input .... value="<?php echo htmlspecialchars($username) ?>" />
<input ...>
</form>
You could always have the form's action submit to itself (same PHP script) and perform your validation there and if it passes continue to another url. And then in your form write some conditionals to insert a CSS class to highlight the field thats in error or show a message.

Categories