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);
}
});
});
Related
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.
I am building an event registration system which displays event registration list if the user is logged in without page refresh using Ajax. However, when I try to login I get undefined index name on line echo "Hello ".$_SESSION["name"]."<br/>"; in index.php. My code is:-
index.php:-
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Registration</title>
<link href="style.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<!--Login div-->
<div id="logincontainer">
<form id="loginform" method="post">
<h3>Login</h3>
<div class="display-error" style="display: none;"></div>
<input type="email" name="lemail" placeholder="Enter email address" required>
<input type="password" name="lpassword" placeholder="Enter password" required>
<input type="submit" value="Sign In">
<p>Forgot Password</p>
<p id="bottom">Don't have an account yet? Sign up</p>
</form>
</div>
<div id="signupcontainer">
<form id="registerform" method="post">
<h3>Register</h3>
<div class="display-error" style="display: none;"></div>
<input type="text" name="rname" placeholder="Full Name" required>
<input type="email" name="remail" placeholder="Enter valid email" required>
<input type="password" name="rpassword" placeholder="Password" required>
<input type="text" name="rmobile" maxlength="10" pattern="[0-9]{10}" placeholder="Mobile" required>
<input type="submit" value="Create Account">
<p id="bottom">Already have an account? Sign In</p>
</form>
</div>
<!--Testing refresh portion-->
<div id="after-login" style="display: none;">
<?php
echo "Hello ".$_SESSION["name"]."<br/>";
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
<!--Testing portion ends-->
</div>
<script>
$(document).ready(function(){
$("#loginform").submit(function(){
var data = $("#loginform").serialize();
checkRecords(data);
return false;
});
function checkRecords(data){
$.ajax({
url : 'loginprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(){
alert("Email/Password is Incorrect");
}
});
}
});
</script>
<!--Signup Ajax-->
<script>
$(document).ready(function(){
$("#registerform").submit(function(){
var data = $("#registerform").serialize();
signupRecords(data);
return false;
});
function signupRecords(data){
$.ajax({
url : 'signupprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
alert('You have successfully Signed Up \n Please Login now.');
setTimeout(function(){
location.reload();
},500);
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(jqXHR,exception){
console.log(jqXHR);
}
});
}
});
</script>
</body>
loginprocess.php
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
$errorMsg = "";
$email = trim($_POST["lemail"]);
$password = trim($_POST["lpassword"]);
if(empty($email)){
$errorMsg .= "<li>Email is required</li>";
}
else{
$email = filterEmail($email);
if($email == FALSE){
$errorMsg .= "<li>Invalid Email Format</li>";
}
}
if(empty($password)){
$errorMsg .= "<li>Password Required.</li>";
}
else{
$password = $password;
}
if(empty($errorMsg)){
$query = $db->prepare("SELECT password from users WHERE email = ?");
$query->execute(array($email));
$pwd = $query->fetchColumn();
if(password_verify($password, $pwd)){
$_SESSION['email'] = $email;
//Testing piece
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email']]);
exit;
}
else{
json_encode(['code'=>400, 'msg'=>'Invalid Email/Password']);
exit;
}
}
else{
echo json_encode(['code'=>404, 'msg'=>$errorMsg]);
}
?>
As far as I can see the problem is that after login call you DO NOT reload the #after-login container contents - you only show it.
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
In the other words the #after-login contents only load on the first page load (before login) and then are not updated by your ajax call (only then you would have access to $_SESSION["name"]).
IMHO proper solution would be to return the $_SESSION["name"] value in the loginprocess.php response and update it in the #after-login container before showing it (eg. use an empty span where the name should appear which you'll fill out on login).
//Something like
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("span#name_placeholder").text(data.name) //return name from loginprocess.php
$("#logincontainer").hide();
$("#after-login").show();
}
The best solution would to be to create a html element like this for the
<div id="after-login" style="display: none;">
<h5 id="Username"></h5>
<?php
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
then after this include the username in the json like this
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
//$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email'],'username'=>$nme]);
exit;
on the ajax call you can now access the json response with the username included and feed the span element with the username like this
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#username").test(data.username);
$("#logincontainer").hide();
$("#after-login").show();
}
I have some issues with my login progress. It logins but it doesn't change the login button to a logout button without manually refreshing the page.
I have a one page jquery plugin that makes the page compact although it doesn't isolate each script from each section.
Here's my page; http://adam-norbacker.ostersjo.nu/
Username: test
Password: password
now here's the plugins and scripts that makes sense about the problem:
https://github.com/davist11/jQuery-One-Page-Nav
Login/logout button:
<div id="menu" class="default">
<ul id="nav">
<?php
session_start();
if(isset($_SESSION['username'])){
$content_hash_name = $_GET['menu'];
if($content_hash_name == 'section-8');
echo "<li><a href='logout.php' class='external'>logout</a></li>";
}else{
echo "<li><a href='#section-8'>login</a></li>";
}
?>
</ul>
</div>
Login script:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
$username = trim(htmlentities(mysql_real_escape_string($_POST['username'])));
$password = trim(htmlentities(mysql_real_escape_string($_POST['password'])));
if (!empty($username) && !empty($password)) {
$_SESSION['username'] = $username;
echo "<br/> welcome ", $username;
} else {
echo "Please enter correct username or password";
}
} else {
echo "please Login";
}
?>
<h1>Login</h1>
<form action="" onSubmit="" method="post">
<label>User Name :</label>
<input type="text" name="username" /><br />
<label>Password</label>
<input type="password" name="password" /><br />
<input type="submit" value="Login" name="submit"/>
</form>
</div>
The only way to do it is using Javascript, because the PHP code will already be parsed.
The easiest way is to use jQuery and do an AJAX call to a PHP page.
Here's the code:
<script type="text/javascript">
$(document).ready(function(){
$("#loginBtn").click(function(){
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
url: 'login.php',
type: 'POST',
data: {username: username, password: password},
dataType: 'json',
success: function(response){
// Success
$("#loginBtn").hide();
$("#logoutBtn").show();
},
error: function(response){
// Error
}
});
return false;
});
$("#logoutBtn").click(function(){
$("#logoutBtn").hide();
$("#loginBtn").show();
return false;
});
});
</script>
<input type="text" value="" id="username" />
<input type="password" value="" id="password" />
<button id="loginBtn">Login</button>
<button id="logoutBtn" style="display:none;">Logout</button>
You don't have to use jQuery to do the thing. Just make sure that PHP script is executed before you output your HTML:
// check login here
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
$username = trim(htmlentities(mysql_real_escape_string($_POST['username'])));
$password = trim(htmlentities(mysql_real_escape_string($_POST['password'])));
if (!empty($username) && !empty($password)) {
$_SESSION['username'] = $username;
$message = "<br/> welcome ", $username;
} else {
$message = "Please enter correct username or password";
}
} else {
$message = "please Login";
}
?>
// here is the menu
// here you can echo any messages that comes from login attempt
if (isset($message)) {
echo $message;
}
// and the login form
Just be sure that whole PHP actions are made before rendering the view.
After the user presses the login button, you run this php script to reload your page.
header("Location:yourpath/yourhomepage.php")
And if you are going to use the login verification in the php and not jquery. You must require to reload the page.
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.
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