jquery-mobile ajax runs one more time after every failed pass - php

I have my html page where people can sign up, which calls my php page for checks and inputs to db,
If i get an error, for example someone does not select their gender it alerts the user as it should. Problem is if the user does not select there gender and submits again the ajax is called twice now and i get two of the same alert messages, If done once more i get three alert messages and this contiunes growing on every press etc. How can i stop this happening.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="css/logout-button.min.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.min.css" />
<link rel="stylesheet" href="css/my.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script src="js/jquery.mobile-1.3.0.min.js"></script>
<script src="js/jquery.cookies.2.2.0.min.js"></script>
<script src="js/account-login.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="account-signup">
<script>
function submitForm() {
$(document).ready(function() {
$("form#signupForm").submit(function() {
var form_data = $('#signupForm').serialize();
$.ajax({
type: "POST",
url: "ajaxResponder.php",
dataType: 'html',
data: form_data,
complete: function(data){
if(data.responseText == 'yes'){
alert("Your Account has been created");
$.mobile.changePage( "account-login.html", { transition: "slide"} );
}else {
alert(data.responseText);
}
}
});
return false;
});
});
}
</script>
<div data-theme="a" data-role="header">
<a data-role="button" href="account-login.html" data-transition="slide"
data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<h3>
Sign-Up
</h3>
</div>
<div data-role="content">
<form id="signupForm" name="signupForm">
<input name="method" id="method" placeholder="method" value="account-signup" type="hidden" />
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="forename">
Forename *
</label>
<input name="forename" id="forename" placeholder="Forename" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="surname">
Surname *
</label>
<input name="surname" id="surname" placeholder="Surname" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<label for="gender">Gender</label>
<select name="gender" id="gender" data-native-menu="false">
<option>Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<div data-role="fieldcontain">
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("ajaxResponder.php?method=account-signup-countries",function(data){
items+='<option value="Select Country">Select Country</option>';
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#countries").html(items);
$("#countries").trigger("change");
});
});
</script>
<legend>Country *</legend>
<select name="countries" id="countries" data-native-menu="false">
</select>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="email">
Email *
</label>
<input name="email" id="email" placeholder="Email" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="password">
Password *
</label>
<input name="password" id="password" placeholder="Password" value="" type="password" />
<label for="confirm">
Confirm Password *
</label>
<input name="confirm" id="confirm" placeholder="Confirm" value="" type="password" />
</fieldset>
</div>
<input data-theme="b" value="Sign-Up" type="submit" onclick="submitForm()" />
</form>
</div>
</div>
</body>
</html>
my php
case 'account-signup':
$password_minlength = 6;
$password_maxlength = 40;
$message == "";
function validusername($username) {
$allowedchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'";
for ($i = 0; $i < strlen($username); ++$i)
if (strpos($allowedchars, $username[$i]) === false)
return false;
return true;
}
$forename= $_POST["forename"];
$surname= $_POST["surname"];
$email= $_POST["email"];
$password= $_POST["password"];
$confirm= $_POST["confirm"];
$day = $_POST["select-choice-day"];
$month = $_POST["select-choice-month"];
$year = $_POST["select-choice-year"];
$country = $_POST["countries"];
$gender = $_POST["gender"];
if ($day =='Day' or $month == 'Mon' or $year =='Year')
$message = "You Need to fill in Your DOB";
if ($gender =='Gender')
$message ="Please select your Gender";
if ($country == "Select Country")
$message ="Please select a Country";
if (empty($password) || empty($forename) || empty($surname) || empty($email) || empty($confirm) )
$message = "All fields required to be filled in";
elseif ($password != $confirm)
$message = "Your passwords do not match";
elseif (strlen($password) < $password_minlength)
$message = sprintf("Your password needs to be more than $password_minlength char");
elseif (strlen($password) > $password_maxlength)
$message = sprintf("Your password needs to be less than $password_maxlength char");
elseif (!validusername($forename))
$message = "Invalid characters used in your forename";
elseif (!validusername($surname))
$message = "Invalid characters used in your surname";
elseif (!validemail($email))
$message = "A Valid email address is required";
if ($message == "") {
// check if email addy is already in use
$a = (#mysql_fetch_row(#SQL_Query_exec("select count(*) from users where email='$email'")));
if ($a[0] != 0)
$message = "Email Address $email has already signed up. Please use account-recovery ";
}
if ($message == "") {
$signupclass = '1';
$status = "confirmed";
$dob = "$year-$month-$day";
$secret = mksecret(); //generate secret field
$password = passhash($password);// hash the password
$forename1 = str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($forename))));
$surname1 = str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($surname))));
SQL_Query_exec("INSERT INTO users (forename,surname, password, secret, email, status, added, last_access, country, gender,dob, stylesheet, language, class, ip) VALUES (" .
implode(",", array_map("sqlesc", array($forename1,$surname1, $password, $secret, $email, $status, get_date_time(), get_date_time(), $country, $gender,$dob, $site_config["default_theme"], $site_config["default_language"], $signupclass, getip()))).")");
$message="yes";
}
echo "$message";
break;

You have an error in your javascript, when calling function, you don't need these lines:
$(document).ready(function() {
$("form#signupForm").submit(function() {
First of all you dont need document ready because you are not waiting for that state. Second thing, if you are using inline hjavascript with onclick=... you dont need to bind a submit event to the form.
Basically each time you call in again you are binding submit event to the form.
Third thing, this would not happen if validation was implemented on a client side, so think about that. You can easily implement jQuery Validate plugin.
My advice to you would be, remove onclick event from this line:
<input data-theme="b" value="Sign-Up" type="submit" onclick="submitForm()" />
Remove onclick function and just use everything like this:
$(document).ready(function() {
$('#signupForm').off('submit').on('submit',function(e) {
var form_data = $('#signupForm').serialize();
$.ajax({
type: "POST",
url: "ajaxResponder.php",
dataType: 'html',
data: form_data,
complete: function(data){
if(data.responseText == 'yes'){
alert("Your Account has been created");
$.mobile.changePage( "account-login.html", { transition: "slide"} );
}else {
alert(data.responseText);
}
}
});
return false;
});
});
Because of submit event this code will trigger when you press submit button, no need for onclick. And notice how submit is handled now:
$('#signupForm').off('submit').on('submit',function(e) {
This will prevent multiple submit events from happening.

Related

How to stay on same page after login

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();
}

Retrieving username and password from Mongodb using php with angular js

I have created a simple login page using mongodb , angular js and php. when the user login from the database by retrieving username and password from the database, it goes to the admin page. But the login from database is not responding as unable to fetch data from db
index.php:
This is the homepage of the website.
<?php
include('login.php'); // Includes Login Script
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>LoginIN</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<link href="styles/bootstrap.min.css" rel="stylesheet">
<link href="styles/signin.css" rel="stylesheet">
</head>
<body>
<?php
if(isset($error) and count($error) > 0){
?>
<div class="errorContainer"> <ul>
<?php foreach($error as $err) echo '<li>'.$err.'</li>'; ?>
</ul></div>
<?php
}
if(!empty($success)){
echo '<p class="text-success">'.$success.'</p>';
}
?>
<div id="wrapper">
<header id="top">
<center><h1>Leave Reporting System</h1></center>
<div class="container">
<div ng-app ='angularPost' ng-controller='loginCtrl'>
<form class="form-signin" role="form" action ="" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="email" name="username" class="form-control" ng-model="username" placeholder="Email address" required autofocus>
<input type="password" name="password" class="form-control" ng-model="password" placeholder="Password" required>
<br>
<div class="checkbox">
<label>
<input type="checkbox" value="remember" name ="remember">Remember me
<br>
</label>
</div>
<input name="submit"button class="btn btn-lg btn-primary btn-block" ng-click=login() type="submit" value=" Sign in">
<span>{{responseMessage}}</span>
<br>
Forgot your password?
</form>
</div>
</body>
</html>
login.php
<?php
$succss = "";
if(isset($_POST['submitForm'] )){
$usr_email = $_POST['username'];
$usr_password = $_POST['password'];
$error = array();
if(empty($usr_email) or !filter_var($usr_email,FILTER_SANITIZE_EMAIL)){
$error[] = "Empty or invalid email address";
}
if(empty($usr_password)){
$error[] = "Enter your password";
}
if(count($error) == 0){
$con = new MongoClient();
if($con){
// Select Database
$db = $con->lrs;
// Select Collection
$Login = $db->Login;
$qry = array("username" => $usr_email,"password" => md5($usr_password));
$result = $Login->findOne($qry);
if($result){
$success = "You are successully loggedIn";
// Rest of code up to you....
}
} else {
die("Mongo DB not installed");
}
}
}
?>
app.js
var app = angular.module('angularPost',[]);
app.controller('loginCtrl', function($scope, $http)
{
$scope.login = function() {
var request = $http({
method : "post",
url : "login.php",
data : {
email : $scope.username,
password: $scope.password
},
});
request.success(function(data)
{
if(data == "1"){
$scope.responseMessage = "Successfully Logged in";
}
else{
$scope.responseMessage= "Username or Password is invalid"
}
});
}
});

Variables not passing between IF statements PHP

Okay so I'm writing a piece of code which checks a number of conditions which are set in IF statements in order to display a button to signup for a website. However, the variables I am declaring as true/false in my IF statements don't seem to be transferring over to the statement where it determined whether they are all true. Ive looked online and can't seem to find any problem like this anywhere, so i don't know if its me being stupid or there is a genuine problem. Here's my code:
<?php
include_once('db_conx.php');
//CHECKING USERNAME IS NOT TAKEN
if(!empty($_POST["username"])) {
$usernameAuth = false;
$username = $_POST['username'];
$sql = "SELECT * FROM users WHERE username='$username'";
$queryUname = mysqli_query($conn, $sql);
$username_check = mysqli_num_rows($queryUname);
if($username_check>0){
echo "Username Not Available.";
} else {
echo "Username Available.";
$usernameAuth = true;
}
}
//CHECKING EMAIL HAS NOT BEEN USED BEFORE
if(!empty($_POST["email"])) {
$emailAuth = false;
$email = $_POST['email'];
$sql = "SELECT * FROM users WHERE email='$email'";
$queryEmail = mysqli_query($conn, $sql);
$email_check = mysqli_num_rows($queryEmail);
if($email_check>0){
echo "Email already registered.";
} else {
$emailAuth = true;
}
}
//CHECKING THAT THE PASSWORDS MATCH AND ARE VALID
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
$passAuth = false;
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
if($password1 != $password2) {
echo "Your passwords do not match.";
} elseif(!preg_match("#[0-9]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Number!";
} elseif(!preg_match("#[A-Z]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Capital Letter!";
} elseif(!preg_match("#[a-z]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Lowercase Letter!";
} else {
$passAuth = true;
}
}
//CHECKING TO SEE IF ALL THE VALIDATION CONDITIONS ARE MET
if(!empty($_POST["checkinput"])){
if(($usernameAuth) && ($emailAuth) && ($passAuth)){
echo '<button id="button" class="btn waves-effect waves-light" type="submit" onclick="signup()" name="action">Register<i class="material-icons right">send</i></button>';
} else {
echo 'shite';
}
}
?>
If you need to know more or want any more pieces of the project, just say and I'm happy to provide them.
UPDATE
Added the AJAX JQUERY and index.php code:
<!DOCTYPE html>
<!--stylesheet -->
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<!-- MaterializeCSS -->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!-- fullPage.js -->
<link rel="stylesheet" type="text/css" href="fullPage.js-master/jquery.fullPage.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="vendors/jquery.easings.min.js"></script>
<script type="text/javascript" src="fullPage.js-master/vendors/jquery.slimscroll.min.js"></script>
<script type="text/javascript" src="fullPage.js-master/jquery.fullPage.js"></script>
<!--TILE SCROLLING-->
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#fullpage').fullpage({
verticalCentered: true,
sectionsColor: ['#1bbc9b', '#2c3e50', '#34495e'],
anchors: ['homepage', 'Login', 'Register'],
afterRender: function(){
//playing the video
$('video').get(0).play();
}
});
});
</script>
<!-- VALIDATING THE NEEDED FIELDS -->
<script type="text/javascript">
//CHECKING USERNAME
function UserAvailability() {
jQuery.ajax({
url: "scripts/validation.php",
data:'username='+$("#username").val(),
type: "POST",
success:function(data){
$("#user-availability-status").html(data);
},
error:function (){}
});
}
//CHECKING EMAIL
function EmailAvailability() {
jQuery.ajax({
url: "scripts/validation.php",
data:'email='+$("#email").val(),
type: "POST",
success:function(data){
$("#email-availability-status").html(data);
},
});
}
//CHECKING PASSWORDS MATCH
function passwordCheck() {
jQuery.ajax({
url: "scripts/validation.php",
data:'password1='+$("#password1").val()+'&password2='+$("#password2").val(),
type: "POST",
success:function(data){
$("#password-status").html(data);
},
});
}
//SIGNUP
function checkInput() {
jQuery.ajax({
url: "scripts/validation.php",
data:'checkinput=success',
type: "POST",
success:function(data){
$("#register-button").html(data);
},
});
}
//CHECKING LOGIN DATA IS VALID
function register() {
jQuery.ajax({
url: "scripts/validation.php",
data:'forename='+$("#firstName").val()+'&surname='+$("#lastName").val(),
type: "POST",
});
}
</script>
</head>
<body>
<div id="fullpage">
<div class="section " id="section0">
<video autoplay loop muted id="myVideo">
<source src="video/homeVideo.mp4" type="video/mp4">
</video>
<div class="layer">
<ul id="menu">
<li data-menuanchor="Login">Login</li>
<li data-menuanchor="Register">Register</li>
</ul>
</div>
<div class="layer">
<h1>Title</h1>
</div>
</div>
<div class="section" id="section1">
<div class="loginCard">
<form action ="scripts/login.php" method="post">
<input type="text" id="usernameLogin" name="username" placeholder="Username">
<input type="password" id="passwordLogin "name="password" placeholder="Password" onblur="loginCheck()">
<span id="login-status"></span>
</form>
</div>
<br>
<div class="registerCard">
<form action="scripts/signup.php" method="post" class="input-field" oninput="checkInput()">
<input type="text" name="firstName" placeholder="First Name" id="first_name" class="validate" >
<input type="text" name="lastName" placeholder="Surname">
<input type="text" nenter code hereame="username" id="username" placeholder="Username" onkeyup="UserAvailability()">
<span id="user-availability-status"></span>
<input type="email" name="email" id="email" placeholder="Email" onkeyup="EmailAvailability()">
<span id="email-availability-status"></span>
<input type="password" name="password" id="password1" placeholder="Password">
<input type="password" name="passwordVerify" id="password2" placeholder="Re-enter Password" onkeyup="passwordCheck()">
<span id="password-status"></span><br>
<span id="register-button"></span>
</div>
</div>
</div>
</body>
The way you are doing it, when these POST params are empty, the variable was never initialized.
A variable that will be used further down and not just inside this if-statement, should have its initial default value initialized outside all the if-statements.
Change
if(!empty($_POST["username"])) {
$usernameAuth = false;
to
$usernameAuth = false;
if(!empty($_POST["username"])) {
AND
if(!empty($_POST["email"])) {
$emailAuth = false;
to
$emailAuth = false;
if(!empty($_POST["email"])) {
AND
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
$passAuth = false;
to
$passAuth = false;
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
Or even better yet, initialize the initial default value of all these flags at the top of the file:
$usernameAuth = false;
$emailAuth = false;
$passAuth = false;
...
if(!empty($_POST["username"])) {
...
if(!empty($_POST["email"])) {
...
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
That will make the logic much cleaner to follow, and leave less room for a mistake.
And then check for more of these oversights.

Form validation to see if the email already excists in the MySQL database

At the moment I have a form (PHP & jQuery) with validations. I want to add a validation to check if the email address of a new user is already in the MySQL database or not.
At the moment there are 3 (IF) validations already for the name and email in jQuery:
function validate() {
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none') {
if(!($("#name").val())) {
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val())) {
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email-error").html("Invalid Email!");
output = false;
}
I would like to have a 4th one to check if the email address is already in the MySQL database.
The complete PHP file with jQuery:
<?php
include 'db_connection.php';
if(isset($_POST['finish'])){
$name = '"'.$dbConnection->real_escape_string($_POST['name']).'"';
$email = '"'.$dbConnection->real_escape_string($_POST['email']).'"';
$password = '"'.password_hash($dbConnection->real_escape_string($_POST['password']), PASSWORD_DEFAULT).'"';
$gender = '"'.$dbConnection->real_escape_string($_POST['gender']).'"';
$sqlInsertUser = $dbConnection->query("INSERT INTO users (name, password, email, gender) VALUES($name, $password, $email, $gender)");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/text.css" />
<link rel="stylesheet" href="css/960.css" />
<link rel="stylesheet" href="css/demo.css" />
<script src="scripts/jquery-1.10.2.js"></script>
<style>
CSS CODE
</style>
<script>
function validate() {
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none') {
if(!($("#name").val())) {
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val())) {
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email-error").html("Invalid Email!");
output = false;
}
}
if($("#password-field").css('display') != 'none') {
if(!($("#user-password").val())) {
output = false;
$("#password-error").html("Password required!");
}
if(!($("#confirm-password").val())) {
output = false;
$("#confirm-password-error").html("Confirm password required!");
}
if($("#user-password").val() != $("#confirm-password").val()) {
output = false;
$("#confirm-password-error").html("Password not matched!");
}
}
return output;
}
$(document).ready(function() {
$("#next").click(function(){
var output = validate();
if(output) {
var current = $(".active");
var next = $(".active").next("li");
if(next.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+next.attr("id")+"-field").show();
$("#back").show();
$("#finish").hide();
$(".active").removeClass("active");
next.addClass("active");
if($(".active").attr("id") == $("li").last().attr("id")) {
$("#next").hide();
$("#finish").show();
}
}
}
});
$("#back").click(function(){
var current = $(".active");
var prev = $(".active").prev("li");
if(prev.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+prev.attr("id")+"-field").show();
$("#next").show();
$("#finish").hide();
$(".active").removeClass("active");
prev.addClass("active");
if($(".active").attr("id") == $("li").first().attr("id")) {
$("#back").hide();
}
}
});
});
</script>
</head>
<body>
<div class="container_12">
<div class="grid_8">
<p>
TEXT<br>TEXT<br>TEXT<br>TEXT<br>TEXT
</p>
</div>
<div class="grid_4">
<p>Register new FC Magnate</p>
<div class="message"><?php if(isset($message)) echo $message; ?></div>
<ul id="signup-step">
<li id="personal" class="active">Personal Detail</li>
<li id="password">Password</li>
<li id="general">General</li>
</ul>
<form name="frmRegistration" id="signup-form" method="post">
<div id="personal-field">
<label>Name</label><span id="name-error" class="signup-error"></span>
<div><input type="text" name="name" id="name" class="demoInputBox"/></div>
<label>Email</label><span id="email-error" class="signup-error"></span>
<div><input type="text" name="email" id="email" class="demoInputBox" /></div>
</div>
<div id="password-field" style="display:none;">
<label>Enter Password</label><span id="password-error" class="signup-error"></span>
<div><input type="password" name="password" id="user-password" class="demoInputBox" /></div>
<label>Re-enter Password</label><span id="confirm-password-error" class="signup-error"></span>
<div><input type="password" name="confirm-password" id="confirm-password" class="demoInputBox" /></div>
</div>
<div id="general-field" style="display:none;">
<label>Gender</label>
<div>
<select name="gender" id="gender" class="demoInputBox">
<option value="female">Female</option>
<option value="male">Male</option>
</select></div>
</div>
<div>
<input class="btnAction" type="button" name="back" id="back" value="Back" style="display:none;">
<input class="btnAction" type="button" name="next" id="next" value="Next" >
<input class="btnAction" type="submit" name="finish" id="finish" value="Finish" style="display:none;">
</div>
</form>
</div>
The "db_connection.php" file:
<?php
define('_HOST_NAME', 'localhost');
define('_DATABASE_USER_NAME', 'root');
define('_DATABASE_PASSWORD', '****');
define('_DATABASE_NAME', '****');
$dbConnection = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);
if ($dbConnection->connect_error) {
trigger_error('Connection Failed: ' . $dbConnection->connect_error, E_USER_ERROR);
}
?>
I tried to create this validation from other examples that were given here on the website. But, no success. Please, it would be great if somebody could help me a little further.
UPDATE: With the help of Suyog I changed the files. But, it doesn't seem to work yet. Here are the files that I use at the moment: fcmagnate.com/files.zip
The form works till the moment the validation of the email address in the database starts, than it stops.
You will have to make use of JQuery AJAX for this.
Write a function in AJAX to send email to php gage where we will check the existance of email.
<script>
function checkEmail(eMail)
{
$.ajax({
url: 'check_email.php',
data: {emailId: eMail},
type: 'post',
success: function (data) {
if(data == '1')
return false;
else
return true;
}
});
}
</script>
Then you can call this function
<script>
function validate()
{
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none')
{
if(!($("#name").val()))
{
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val()))
{
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
$("#email-error").html("Invalid Email!");
output = false;
}
if(!checkEmail($("#email").val()))
{
$("#email-error").html("Email already exist!");
output = false;
}
}
}
</script>
Youe check_email.php file will contain the code as follows
<?php
include 'db_connection.php';
if(isset($_POST['emailId']))
{
$email = '"'.$dbConnection->real_escape_string($_POST['emailId']).'"';
$sqlCheckEmail = $dbConnection->query("SELECT user_id FROM users WHERE LOWER(email) like LOWER('%".$email."%')");
if($sqlCheckEmail->num_rows == 1)
echo '1';
else
echo '0';
}
?>
Use Ajax jQuery.ajax on client side to communicate with server side reusing your php code mentioned.

php call function from another class

I am trying to call a function with arguments from another class. The class with the function I need to call is auth.class.php (it's pretty long so I've shorten to the relevant class). I've a index.php file with jQuery form that when post calls reg.php and sends data their. I want to call the register function in auth.class.php file from the reg.php
I am not sure what I am doing wrong, I think the ajax might be the problem but any help will be appreciated.
auth.class.php
<?php
class Auth {
public function register($email, $username, $password, $repeatpassword)
{
$return = array();
$return['code'] = 400;
if ($this->isBlocked()) {
$return['code'] = 0;
return $return;
} else {
$validateEmail = $this->validateEmail($email);
$validateUsername = $this->validateUsername($username);
$validatePassword = $this->validatePassword($password);
if ($validateEmail['error'] == 1) {
$return['message'] = $validateEmail['message'];
return $return;
} elseif ($validateUsername['error'] == 1) {
$return['message'] = $validateUsername['message'];
return $return;
} elseif ($validatePassword['error'] == 1) {
$return['message'] = $validatePassword['message'];
return $return;
} elseif($password !== $repeatpassword) {
$return['message'] = "password_nomatch";
return $return;
} else {
if (!$this->isEmailTaken($email)) {
if (!$this->isUsernameTaken($username)) {
$addUser = $this->addUser($email, $username, $password);
if($addUser['error'] == 0) {
$return['code'] = 200;
$return['message'] = "register_success";
return $return;
} else {
$return['message'] = $addUser['message'];
return $return;
}
} else {
$this->addAttempt();
$this->addNewLog("", "REGISTER_FAIL_USERNAME", "User attempted to register new account with the username : {$username} -> Username already in use");
$return['message'] = "username_taken";
return $return;
}
} else {
$this->addAttempt();
$this->addNewLog("", "REGISTER_FAIL_EMAIL", "User attempted to register new account with the email : {$email} -> Email already in use");
$return['message'] = "email_taken";
return $return;
}
}
}
}
}
This is my html file index.php I am using jQuery mobile with ajax
<!DOCTYPE html>
<html>
<head>
<title>
Submit a form via AJAX
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />
<script src="http://code.jquery.com/jquery-1.5.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js">
</script>
</head>
<body>
<script>
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
function onError(data, status)
{
// handle an error
}
$(document).ready(function()
{
$("#submit").click(function()
{
var formData = $("#Register").serialize();
$.ajax(
{
type: "POST",
url: "reg.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
<!-- call ajax page -->
<div data-role="page" id="callAjaxPage">
<div data-role="header">
<h1>
Call Ajax
</h1>
</div>
<div data-role="content">
<form id="Register">
<div data-role="fieldcontain">
<label for="Email">
eMail
</label>
<input type="email" name="email" id="email" value="" />
<br />
<label for="UserName">
User Name
</label>
<input type="text" name="username" id="username" value="" />
<br />
<label for="Password">
Password
</label>
<input type="password" name="password" id="password" value="" />
<br />
<label for="Confirmpassword">
Confirm Password
</label>
<input type="password" name="repeatpassword" id="repeatpassword" value="" />
<h3 id="notification">
</h3>
<button data-theme="b" id="submit" type="submit">
Submit
</button>
</div>
</form>
</div>
<div data-role="footer">
<h1>
GiantFlyingSaucer
</h1>
</div>
</div>
</body>
</html>
This is my the php file that's placing the call the auth.class.php function.
<?php
include_once "password.php";
require_once "auth.class.php";
$mail = $_POST[email];
$usn = $_POST[username];
$pswd = $_POST[password];
$cpswd = $_POST[repeatpassword];
$register = new Auth();
$register ->register($mail, $usn, $pswd, $cpswd);
echo $return;
?>
Make index.php all the code is here and ajax function also here and make calls.php which is call by ajax function and calls.php file call your class.auth.php file.
you didn't assign the value returned by your function to anything.
Try this:
$return= $register ->register($mail, $usn, $pswd, $cpswd);
echo $return;
Here's the updated code that fixed the problem. I wasn't passing the data as an array serializeArray and also made some changes in the reg.php class as well.
New index.php file
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Mobile: Theme Download</title>
<link rel="stylesheet" href="themes/Carelincs.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.3/jquery.mobile.structure-1.4.3.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
</head>
<body>
<script>
$(document).ready(function()
{
$("#submit").click(function()
{
var formData = $("#register").serializeArray();
$.ajax(
{
type: "POST",
url: "../pages/register.php",
cache: false,
data: formData,
success: onSuccess,
});
return false;
});
});
function onSuccess(data, status)
{
data = $.trim(data);
$("#message").text(data);
}
function onError(data, status)
{
//Handle error
}
</script>
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1>Header</h1>
</div>
<div data-role="content" data-theme="a">
<form action="" method="POST" id="register">
<label for="email">Email:</label>
<input type="email" name="email" placeholder="eMail"/>
<br />
<label for="username">Username:</label>
<input type="text" name="username" placeholder="User Name"/>
<br />
<label for="password">Password:</label>
<input type="password" name="password" placeholder="Password"/>
<br />
<label for="confirm password">Confirm Password</label>
<input type="password" name="repeatpassword" placeholder="Confirm Password"/>
<br />
<button type="submit" id="submit">Submit</button>
</form>
<p id="message"></p>
</div>
</div>
</body>
</html>
new reg.php file I also added information to connect to database.
<?php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host=" . $config-> dbhost . ";dbname=" . $config->dbname, $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
$repeatpassword = $_POST["repeatpassword"];
$register = $auth->register($email, $username, $password, $repeatpassword );
// Temporary just to see what's going on :
var_dump($register);
?>

Categories