JQuery event.preventdefault and php - php

I have a question concerning event.preventdefault. I used it on my client side validation just to make sure a username and password were filled in. However when I pressed the submit button and passed the validation on to php I got nothing. I mean when I checked if the form was submitted and did an echo to check I got nothing. But when I did (!isset($_POST['whatever']) I got something. Same goes for check if the fields were empty. I got nothing when I did empty, but got something when I did !empty
Jquery/html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/verneyCustom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<!-- cms login form -->
<form action="login.php" method="POST" class="form-signin" id="cms-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<span class="text-center" id="jsError"></span><!-- display client side errors -->
<input type="text" class="form-control" id="username" placeholder="Username" autofocus><br/>
<input type="password" class="form-control" id="password" placeholder="Password"><br/>
<input type="submit" class="btn btn-lg btn-primary btn-block" id="loginToSystem" value="Sign In">
</form>
</div>
<!-- include jquery v1.10.2 library to validate client side -->
<script src="js/jquery.js"></script>
<script>
//if the form is submitted check if values are ok
$("#cms-signin").submit(function(event){
if($('#username').val() == "" || $('#password').val() == ""){
event.preventDefault();
$("#jsError").html('You must fill in the form.');
}else if($('#username').val() == ""){
event.preventDefault();
$("#jsError").html('Username is required.');
}else if($('#password').val() == ""){
event.preventDefault();
$("#jsError").html('Password is required.');
}
});
</script>
</body>
</html>
php code
<?php
//include the connection to the cms database
require_once($_SERVER['DOCUMENT_ROOT'].'/vcm/_cms/resources/database_connect.php');
//check if the form was sent
if(isset($_POST['loginToSystem'])){
echo 'o';
//create an array for errors
$errors = array();
//check if the username and password fields are empty
//yes we did a check if jquery on the front but some people disable javascript
if(empty($_POST['username']) || empty($_POST['password'])){
echo 'empty';
}else{
echo 'ok';
}
}
echo'p';
?>
So basically it echo's 'p' no matter what, but will only echo 'o' if isset is changed to !isset. It will echo empty when left as is, and ok when changed to !empty

as adeneo explained you must add name
<form action="login.php" method="POST" class="form-signin" id="cms-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<span class="text-center" id="jsError"></span><!-- display client side errors -->
<input type="text" class="form-control" name="username" id="username" placeholder="Username" autofocus><br/>
<input type="password" class="form-control" name="password" id="password" placeholder="Password"><br/>
<input type="submit" class="btn btn-lg btn-primary btn-block" id="loginToSystem" value="Sign In">
</form>
also you need && not ||
$("#cms-signin").submit(function(event){
if($('#username').val() == "" && $('#password').val() == ""){
event.preventDefault();
$("#jsError").html('You must fill all fields.');
}
});

Related

How do I include array from another PHP file

In the handle_signup.php page, I try to handle with the data which was sent from the sign up page. If the nickname blank has no value, then the error message is "Please enter your nickname". So, in the signup page, I try to include the $errorMsgs array from handle_signup.php page and show the msg below the nickname input. How can I get the array from the handle_signup.php page? Currently, I use include_once, but there is no message in the array after transferring to handle_signup.php. Could some one help this issue? Thank you.
Handle the value from signup.php
<?php
require_once('./conn.php');
$errorMsgs = array('nickname'=>'', 'email'=>'', 'password'=>'');
if(isset($_POST['submit'])) {
if(empty($_POST['nickname'])) {
$errorMsgs['nickname'] = "Please enter your nickname";
header("Location: ./signup.php");
}
};
?>
Sign up page - signup.php
<?php
include_once 'handle_signup.php';
var_dump($errorMsgs);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" />
<title>Message Board - Sign Up</title>
</head>
<body>
<div class="container_sign">
<h1 class="title">Create Account</h1>
<form class="sign" method="POST" action="./handle_signup.php">
<div>
<i class="far fa-user"></i>
<input type="text" placeholder="Nickname" name="nickname">
</div>
<p class="warning__msg"></p>
<div>
<i class="far fa-envelope"></i>
<input type="text" placeholder="Email" name="email">
</div>
<p class="warning__msg"></p>
<div>
<i class="fas fa-lock"></i>
<input type="password" placeholder="Password" name="password">
</div>
<p class="warning__msg"></p>
<input type="submit" value="SIGN UP" name="submit">
</form>
</div>
</body>
</html>
As DarkBee suggested, you can use $_SESSION for your error messages, or simply don't use header("Location: ./signup.php") but include all your PHP code in the same page.

Failed to login even credentials are exactly right in laravel login

I made a login form, while I used to enter credentials, my email and password are absolutely correct, but this code shown me an error, that I defined in else condition. please help me to find my mistake.
loginstudent.blade.php (login form)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<title>Login</title>
</head>
<body>
<div class="container">
<table class="table table-striped">
<form action="{{route('matchlogin')}}" method="post">
#csrf
<div class="container">
<label for="uname"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required/> <br/>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pwd" required/> <br/>
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<input type="submit" name="submit" value="Login"/>
</form>
</table>
</div>
#if(\Session::has('notmatch'))
<div class="container">
<h2> {{\Session::get('notmatch')}} </h2>
</div>
#endif
</body>
</html>
studentcontroller.php (controller function)
public function matchlogin(Request $request)
{
$email = $request->email;
$password = $request->pwd;
if (Auth::attempt(array('email' => $email, 'password' => $password))) {
return "success";
} else {
$request->session()->flash('notmatch', 'Email & password not match');
return redirect(route('loginstudent'));
}
}
web.php (Routes)
Route::get('/loginstudent','studentcontroller#login')->name('loginstudent');
Route::post('/checklogin','studentcontroller#matchlogin')->name('matchlogin');
How did you save your password? Is it hashed and then saved? Because Auth::attempt matches the hashed pattern. If your password is saved in simple text or in some other encryption form, it won't work and will give mismatch.
Thanks

Google ReCaptcha Display with Image & Client Side Validation on Form Submit

I have followed
How to Validate Google reCaptcha on Form Submit
I have below code in my index.php
<!DOCTYPE HTML>
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form method="post" action="post.php">
<div class="g-recaptcha" data-sitekey="6XXXXXXXXXXXXwdsf0K8HbXXXXXXX"></div>
<input type="submit" value="Submit" />
</form>
</body>
</html>
post.php
$response = $_REQUEST['g-recaptcha-response'];
$secret = '6XXXXXXXXXXXXwdsf0K8HbJNvMw-XXXX';
$server = $_SERVER['REMOTE_ADDR'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $response.'&remoteip='.$server);
$response = json_decode($response, true);
if ($response["success"] === true) {
echo "Logged In Successfully";
} else {
echo "You are a robot";
}
exit;
Above code is working fine.
How to do client side validation? It's not showing Captcha with Images Option.
I already done below
This is the standard behavior of the Recaptcha library does not display the first time the control over the images.
Try to view or post the page many times and you will see that the images not eventually appear.
If you want to do some client side validation on other additionnals fields, you must use jQuery or standar library like bootstrap or foundation, like this or this. You can see of full example of a working script here (inspired from bootstrap script and HTML 5 capabilities) :
This version of the script is the same all over Internet. No more client side validation for this ! Have a look to a reference : codepen.io signup
For example :
<!DOCTYPE HTML>
<html>
<head>
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form class="signin-form" method="post" action="post.php">
<!-- for example : Email and password validation (HTML 5) -->
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<!-- Site-key for automated tests -->
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body>
</html>
And here a sample code pen.

php form action with recaptcha check

Working on a simple contact form, and I'm trying to integrate Google ReCaptcha to eliminate the spam I started receiving.
Right now it's checking to see if the ReCaptcha is successful. If it's not, it just currently reloads the page and resets the form. If it is, I'd like it to fire the receiving contact form php page and pass the form values along with it.
It's getting hung up on that part. Any help would be greatly appreciated.
<?php
// grab ReCaptcha library
require_once "recaptchalib.php";
// your secret key
$secret = "XXXXXXXXXXXXXXXXXXXXXXXX";
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Contact Form</title>
<link href='https://fonts.googleapis.com/css?family=Work+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="assets/form-basic.css">
</head>
<body>
<div class="main-content">
<?php
$action = '';
if ($response != null && $response->success) {
$action = "contactengine.php";
} else {
?>
<form class="form-basic" action="<?php echo $action ?>" method="post">
<div class="form-title-row">
<h1>Get in Touch</h1>
</div>
<div class="form-row">
<input type="text" name="Name" placeholder="Name" required>
</div>
<div class="form-row">
<input type="email" name="Email" placeholder="Email" required>
</div>
<div class="form-row">
<textarea name="Message" placeholder="Message" required></textarea>
</div>
<div class="form-row">
<div class="g-recaptcha" data-sitekey="fdgafafdadfgsdfgrafgaRlifgsfgserysrtyc3H"></div>
</div>
<div class="form-row">
<button type="submit" name="submit" value="submit">Send</button>
</div>
</form>
<?php } ?>
</div>
<script src='https://www.google.com/recaptcha/api.js?hl=en'></script>
</body>
</html>
You can either move the captcha checking code into the receiving contact form page, or add the contact form processing logic in the main page. You probably want to use the last approach.

PHP Error? in Password or Username

I have two files connect.php and login.php. The login script returns a user_id or password error, but I know they are correct.
The DB connection seems to be working OK and I cannot see any specific fault in the PHP code in login.php.
Can anyone spot the error or point me in the right direction.?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Login</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="user_id" class="sr-only">Email address</label>
<input type="email" id="user_id" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="password" class="form-control" placeholder="Password" required>
<div class="checkbox">
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log-in</button>
</form>
</div> <!-- /container -->
<?php //start php tag
//include connect.php page for database connection
Include('connect.php');
//if submit is not blanked i.e. it is clicked.
if (isset($_REQUEST['Submit'])) //here give the name of your button on which you would like //to perform action.
{
// here check the submitted text box for null value by giving there name.
if($_REQUEST['user_id']=="" || $_REQUEST['password']=="")
{
echo " Field must be filled";
}
else
{
$sql1= "select * from users where email= '".$_REQUEST['user_id']."' && password ='".$_REQUEST['password']."'";
$result=mysql_query($sql1)
or exit("Sql Error".mysql_error());
$num_rows=mysql_num_rows($result);
if($num_rows>0)
{
// redirect
header("Location:ncr.php");
}
else
{
echo "username or password incorrect";
}
}
}
?>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
This is the DB connection, but it looks fine.
<?php
$hostname="localhost";
$username="xxx";
$password="xxxx";
$database="xxx";
$con=mysql_connect($hostname,$username,$password);
if(! $con)
{
die('Connection Failed'.mysql_error());
}
mysql_select_db($database,$con);
?>
In your html form must put the name of the input for the php can take the values:
<input type="email" name="user_id" id="user_id" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="password" id="password" class="form-control" placeholder="Password" required>
I hope it helps you...

Categories