form data saved in localstorage and post to php - php

I am working on a simple login form for a mobile site that will save the form data in local storage but will also post data to a php file for url redirection with appended form data. I need help as the storage is working but the post for this is not.
Html
<form class="form-signin" action="siteurl/processing/login-app.php" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" placeholder="Eventname" id='eventname'>
<input type="text" class="input-block-level" placeholder="Username" id='username'>
<input type="password" class="input-block-level" placeholder="Password" id="password">
<label class="checkbox">
<input type="checkbox" value="remember-me" id="remember_me"> Remember me
</label>
<button class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
Now the script
<script>
$(function() {
if (localStorage.chkbx && localStorage.chkbx != '') {
$('#remember_me').attr('checked', 'checked');
$('#username').val(localStorage.usrname);
$('#pass').val(localStorage.pass);
} else {
$('#remember_me').removeAttr('checked');
$('#username').val('');
$('#pass').val('');
}
$('#remember_me').click(function() {
if ($('#remember_me').is(':checked')) {
// save username and password
localStorage.usrname = $('#username').val();
localStorage.pass = $('#pass').val();
localStorage.chkbx = $('#remember_me').val();
} else {
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});
});
</script>
And the php
<?php
if (isset($_POST["eventname"]) && isset($_POST["username"]) && isset($_POST["password"])) {
$eventname = $_POST["eventname"];
$username = $_POST["username"];
$password = $_POST["password"];
$url = "siteurl/index.php/$eventname?user=$username&passw=$password";
header( "Location: $url" ) ;
} else {
echo "Username and Password not found";
}
?>
What am I missing?

Your POST variables work off the input names, not ids.
Add a name attribute to your inputs and access them.

Related

What's wrong with my AJAX and PHP whern I call it to login?

I have some trouble with my login form using ajax and php, could somebody con solve this??
This is code html:
login.html
<div id="id01" class="modal">
<form class="modal-content animate" action="" method="POST" id="login-form">
<div class="container">
<label for="login-email"><b>Username</b></label>
<input type="text" placeholder="Enter Email" id="login-email" name="login-email" required>
<label for="login-password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="login-password" name="login-password" required>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label><br>
<span id="showError"></span>
<button type="submit" id="btn-login" name="btn-login">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancel-btn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#btn-submit").click(function{
var login-email = $("#login-email").val();
var login-password = $("#login-password").val();
var error = $("#showError");
if(login-email != "" && login-password != ""){
$.ajax({
url: "checkLogin.php",
type: "POST",
data: { login-email: login-email, login-password: login-password},
success: function(response){
var msg = "";
if(response == "success"){
window.location = 'profile.php';
} else {
msg = "Tên đăng nhập hoặc mật khẩu không chính xác.";
}
$('#id01').css({"display": "block"});
error.html(msg);
}
});
} else {
error.html("Email đăng nhập hoặc mật khẩu không được bỏ trống.");
return false;
}
});
});
</script>
and this is code php
login.php
if(isset($_POST["btn-login"])){
$email = trim($_POST["login-email"]);
$password = trim($_POST["login-password"]);
$sql_login = "SELECT email, password, permission FROM users where email='$email' and password='$password'";
$db->query($sql_login);
$rows = $db->findOne();
$permission = $rows['permission'];
if($rows['email'] == $email && $rows['password'] == $password){
echo "success";
} else {
echo "fail";
}
exit();
}
It seem to be not to load into ajax and php code cause i've try so many time but i didn't know the bugs in here.
you call checkLogin.php but the code php is in login.php
In the login.php code, you check the btn-login but the post data from client have no btn-login
{ login-email: login-email, login-password: login-password}
so the if block will never work.
if(isset($_POST["btn-login"])){
...
}
you can change like this
if(isset($_POST["login-email"]) && isset($_POST["login-password"])){
...
}
It appears at first glance that your jQuery is referencing btn-submit but your html defines this as btn-login instead.

My php vairables are not working properly beacuse of jQuery

Whenever I hit submit button my first name, last name and email are empty even when they are filled up properly so they return red color fonts.
Here is the PHP code:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$college = mysqli_real_escape_string($conn, $_POST['college']);
$pwd = mysqli_real_escape_string($conn, $_POST['password']);
// Error handlers
$errorfirst=false;
$erroremail=false;
$errorlast=false;
$errorpwd=false;
// Check for empty fields
if (empty($first) || empty($email) || empty($pwd)) {
echo "
<span class='form-error'>*Please check one of the fields before submitting<br></span>
<span class='form-error'>*Please check first name <br></span>
<span class='form-error'>*Please check last name <br></span>
<span class='form-error'>*Please check email <br></span>
";
$errorfirst=true;
$erroremail=true;
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
echo "<span class='form-error'>*write properly</span>";
$errorfirst=true;
$errorlast=true;
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>*write a proper email</span>";
} else {
$sql = "SELECT * FROM name WHERE user_email='$email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo "<span class='form-error'>This E-mail ID is already existed</span>";
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO name (id,user_first, user_last, user_email, user_uid, user_pwd) VALUES (NULL,'$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
}
}
}
}
} else {
header("Location: ../signupform.php");
exit();
}
?>
<script type="text/javascript">
$('.first-input,.last-input,.email-input').removeClass('input-error');
var errorfirst="<?php echo '$errorfirst'; ?>";
var errorlast="<?php echo '$errorlast'; ?>";
var erroremail="<?php echo '$erroremail'; ?>";
if (errorfirst==true) {
$('.first-input').addClass('input-error');
}
if (errorlast==true) {
$('.last-input').addClass('input-error');
}
if (erroremail==true) {
$('.email-input').addClass('input-error');
}
if (erroremail==false && errorfirst==false && errorlast==false) {
$('.first-input,last-input,.email-input').val('');
}
</script>
It is not sending any value to the database. I used jQuery to validate form without refreshing but I think because of jQuery my form is not working
Here is my jQuery code
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$(".first-input").val();
var last=$(".last-input").val();
var email=$(".email-input").val();
var college=$(".college-input").val();
var password=$(".password-input").val();
var submit=$(".signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>
And here is my HTML form
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button type="submit" name="button">sign-up</button>
</div>
</form>
Help me over this issue and I also don't know about security in PHP forms so you can aslo suggest me some tips over that, I will really appreciate because I am want to be a professional back-end developer and now I am a newbie
Your jQuery uses $(".first-input").val(), but you have class="first-input" on the DIV, not the input.
Either move the class attribute to the inputs, or change the selector to $(".first-input input").val() (and similarly for all the other inputs).
You need to grab the input, not the container
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input id="first-input" type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input id="last-input" type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input id="email-input" type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input id="college-input" type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input id="password-input" type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button id="signup-btn" type="submit" name="button">sign-up</button>
</div>
</form>
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$("#first-input").val();
var last=$("#last-input").val();
var email=$("#email-input").val();
var college=$("#college-input").val();
var password=$("#password-input").val();
var submit=$("#signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>

check if value exist in json file using php

i make a login system using php with json file data. i tried to login with JavaScript file and it works fine. but it is not secure well. then i change some code with php login.
this is my php code
if(isset($_POST['submit'])){
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
foreach($parsed_json as $key => $value){
$jsonemail = $value['email'];
$jsonpass = $value['pass'];
}
if($email == $jsonemail && $pass == $jsonpass){
header('location: view.php');
}
else{
echo "please check your email or password";
}
}
but this not working. i want to fix this code. i want to check email and password is correct with json file data.
this is my login.json file data like
"1": {
"email": "test123#gmail.com",
"pass": "123"
},
and this is my html login form
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" id="email" aria-describedby="emailHelp" required="require" placeholder="Enter email">
</div>
<div class="form-group">
<label for="pass">Password</label>
<input type="password" class="form-control" id="pass" required="require" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" name="submit" >Submit</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
</div>
I think your email and pass variable are not defined. Have a look at it.
if (isset($_POST['submit'])) {
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
$email = $_POST['email']; // I think you miss this
$pass = $_POST['pass']; // and this lines as in your code its missing
$flag = false;
foreach ($parsed_json as $key => $value) {
if ($value['email'] == $email && $value['pass'] == $pass) {
$flag = true;
break;
}
}
if ($flag) {
header('location: view.php');
} else {
echo "Please check your email and password."
}
}
And one more thing
while posting any form you must name element which you want in $_POST.
<input type="password" class="form-control" id="pass" required="require" placeholder="Password">
In above line you are missing name as pass. Replace above line with
<input type="password" class="form-control" id="pass" required="require" placeholder="Password" name="pass">
This should solve your problem.
Your foreach is just overwriting the values of $jsonemail and $jsonpass each time, so when you reach the if() part to check the user details, these will always be the last values in the file.
if(isset($_POST['submit'])){
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
foreach($parsed_json as $key => $value){
if($email == $value['email'] && $pass == $value['pass']){
header('location: view.php');
exit();
}
}
echo "please check your email or password";
}
This code redirects if the user is found and if it gets to the end of the loop, then the user doesn't exist in the file.

Why is this jQuery function not communicating properly with my php file?

Let me show you what I have:
(1) Form:
<form name="login-form" class="login-form" method="post" onSubmit="login()">
<div class="header">
<h1>Sign In</h1>
</div>
<div class="content">
<input type="hidden" name="siteToken" value="$token" />
<input id="username" name="username" type="text" class="input username" placeholder="Username" required="required" />
<div class="user-icon"></div>
<input id="password" name="password" type="password" class="input password" placeholder="Password" required="required" />
<div class="pass-icon"></div>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button" />
</div>
</form>
(2) jQuery Function:
$(document).ready(function login() {
$('.login-form').submit(function() {
var formData = $(this).serialize();
$("input").prop("disabled", true);
$.post('VRC_LoginProcess.php', formData, loginMessage);
function loginMessage(data) {
$('.header').append(data);
};
});
});
(3) PHP Function:
<?php
require_once('VRC_Header.php');
require_once('../Classes/VRC_MasterOO.php');
require_once('../Classes/VRC_Secure_Login.php');
//*******************************//
//Declerations
$signIn = "";
$username = "";
$password = "";
$success = "";
$error = "";
//******************************//
//****************************************************************************************//
//Script Header
$signIn = new UserService($dbuser, $dbpass, $dbhost, $dbname); //Create new class instance
$signIn->sec_session_start(); //Begin session
//***************************************************************************************//
//***************************************************************************************//
//Begin Login Functions
if(isset($_POST['username'], $_POST['password'])) {
//Assign POST submissions to passable php variables
$username = $_POST['username'];
$password = $_POST['password'];
$passedToken = $_POST['siteToken'];
/*//Check Token Values (prevent CSRF attacks)
if($passedToken != $_SESSION['token']) {
$error = "CSRF attack detected. Please close your browser and try again.";
$signIn->csrfAttackLog($username);
echo $error;
exit();
}*/
//Test if both fields are not null
if($username == "" || $password == "")
{
$error = "Not all fields were entered<br />";
echo $error;
exit();
}
//Start login process
else
{
$success = $signIn->login($username, $password);
if ($success === true)
{ //Login Successful
echo "Success!"; //Direct to main page.
exit();
}
//Specific login failure determination
else
{
switch ($success){
case 1:
$error = "Your account has been locked.";
echo $error;
break;
case 2:
$error = "Invalid Username/Password (2)";
echo $error;
break;
case 3:
$error = "Invalid Username/Password";
echo $error;
break;
case 4:
$error = "Invalid Username/Password (3)";
echo $error;
break;
}
}
}
}
?>
Fist off, I doubt the problem is in the PHP function. I've tested it before implementing jQuery calls (I used it directly in the html action attribute). My suspicion is that the problem is occurring in the jQuery function (I just started using jQuery and am not really familiar with it).
Note that I have removed the token input for the time being in the php file. I simply want to get it working before I deal with that (there is another problem with that part).
I don't believe that the post variables are being sent to the php file correctly. Also, I don't believe my jQuery function as it is is properly receiving the echo response from my php function either, in the sense that it will display it as html - provided that it worked to begin with.
Any input is appreciated.
$(document).ready(function login() {
That line is the problem.
Probably the login function is not available to rest of the page. It's just a name given to anonymous function which is parameter to $(document).ready function.
You have a scope problem.
Move the login function out separately:
function loginMessage(data) {
$('.header').append(data);
};
function login() {
$('.login-form').submit(function () {
var formData = $(this).serialize();
$("input").prop("disabled", true);
$.post('VRC_LoginProcess.php', formData, loginMessage);
});
}
$(document).ready(function () {
login();
});
EDIT:
in your login function, you are registering a handler to your login form's submit event. And it has to be registered only once.
So, remove `onsubmit=login()` from your form's attributes, and you are good.
Slightly Changed your HTML to this
<form name="login-form" class="login-form" method="post">
<div class="header">
<h1>Sign In</h1>
</div>
<div class="content">
<input type="hidden" name="siteToken" value="$token" />
<input id="username" name="username" type="text" class="input username" placeholder="Username" required="required" />
<div class="user-icon"></div>
<input id="password" name="password" type="password" class="input password" placeholder="Password" required="required" />
<div class="pass-icon"></div>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button" />
</div>
</form>
and Javascript
$(document).ready(function () {
$('.login-form').submit(function (e) {
e.preventDefault();
var formData = $(this).serialize();
$("input").prop("disabled", true);
$.post('VRC_LoginProcess.php', formData, loginMessage);
function loginMessage(data) {
$('.header').append(data);
}
});
});

Ajax PHP + MySQL registration form tutorial

Until now I have
HTML
<form id="account_reg" action="reg.php" method="post">
<div id="response"></div>
<div class="input">
<label>Login</>
<input name="login" type="text" class="required" id="login" size="30"/>
</div>
<div class="input">
<label>Password</>
<input name="password" type="text" class="required" id="password" size="30"/>
</div>
<div class="input">
<label>Repeat Password</>
<input name="rpassword" type="text" class="required" id="rpassword" size="30"/>
</div>
<div class="input">
<label>Email</>
<input name="email" type="text" class="required" id="email" size="30"/>
</div>
<div class="button">
<input type="submit" name="send" id="send" value="Send"/>
</div>
<div class="input">
<input type="hidden" name="honeypot" id="honeypot" value="http://"/>
<input type="hidden" name="humancheck" id="humancheck" class="clear" value=""/>
</div>
</form>
MY PHP
I have some validation on server side.
`
include("dop/config.php"); //includ Db connect
$login = ($_POST['login']);
$password = ($_POST['password']);
$rpassword = ($_POST['rpassword']);
$email = ($_POST['email']);
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];
if ($honeypot == 'http://' && empty($humancheck)) {
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-Za-Z.](2,4)$/";
if(!preg_match($reg_exp, $email)){
$error_message .="<p>A Valid email is required</p>";
}
if(empty($login)){
$error_message .="<p>enter login</p>";
}
if(empty($password)){
$error_message .="<p>Enter password</p>";
}
if(empty($rpassword)){
$error_message .="<p>Enter password again</p>";
}
if($password != $rpassword){
$error_message .="<p>password mut match</p>";
}
}
else {
$return['error'] = true;
$return['msg'] = "<h3>There was a problem with your submission. Please try again.</h3>";
echo json_encode($return);
}
My JS
With Validation.
$('#send').click(function(e)
{
e.preventDefault();
var valid = '';
var required =' is required.';
var login = $('#account_reg #login').val();
var password = $('#account_reg #password').val();
var rpassword = $('#account_reg #rpassword').val();
var email = $('#account_reg #email').val();
var honeypot = $('#account_reg #honeypot').val();
var humancheck = $('#account_reg #humancheck').val();
if(login = ''){
valid ='<p> Your Name '+ required +'</p>';
}
if(password='' || company.length<=6){
valid +='<p> Password '+ required +'</p>';
}
if(rpassword != password){
valid +='<p> password must match </p>';
}
if(!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i))
{
valid +='<p> Your Email' + required +'</p>';
}
if (honeypot != 'http://') {
valid += '<p>Spambots are not allowed.</p>';
}
if (humancheck != '') {
valid += '<p>A human user' + required + '</p>';
}
if(valid !=''){
$('#account_reg #response').removeClass().addClass("error")
.html('<strong> Please Correct the errors Below </strong>' + valid).fadeIn('fast');
}
else{
//$('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('#account_reg').serialize();
$('#send').val("Please wait...");
submitForm(formData);
}
});
function submitForm(formData) {
$.post('reg2.php',formData, function(data){
//console.log(data);
$('#send').val("Send");
if (data === '1') {
alert('ok!');
} else {
alert('wrong shit');
}
});
};
I didn't do yet the MySQL part With Inserting and checking if account is already registered.
The first problem that I have is on Click event redirects me on reg.php even when I use e.preventDefault();
If anybody knows a good tutorial for creating registration form or any suggestion.
The form is submitted, that is why you get to reg.php. From what I see you are submitting the data with a custom function anyway so the quickest way to fix that would be to change the submit input into a regular button. So
<input type="submit" name="send" id="send" value="Send"/>
becomes
<input type="button" name="send" id="send" value="Send"/>
I think that it might also help if you return false when you find an error in the function that validates the form when.
A side question: I find it strange that you chose to have a honeypot field with a value (http://). Usually those fields are empty.. Is there any specific reason for doing so?
You need to keep all your JS code expect function submitForm(formData) inside $(document).ready(function(){});
If I'm not wrong there is no variable with name company so change this variable to password i,e. in second if condition of your validation.
Note: If some errors exist in your code then don't escape from those errors instead try to debug it.
there is something wrong with JS code when the code is not working
maybe you can try from this example for SignupForm using JQuery http://bit.ly/1aAXy5U

Categories