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.
Related
Whilst trying to use AJAX for validation on my website, it is completely displaying to the user with exception of the PHP variables, the jquery code I am using for styling my inputs. I am trying to change the styles of my inputs accordingly and provide and error message, which is successful, however, the javascript code is also being displayed
index.php
<html>
<head>
<link rel="stylesheet" href="css/template.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="jquery/template.js"></script>
<script type="text/javascript" src="jquery/index.js"></script>
</head>
<body onload="startUp();">
<!-- Banner Image -->
<div id="banner"><img id="bannerImage" src="abcdefd.com.jpg" alt=""></div>
<!-- Body Wrapper -->
<div id="wrapper">
<!-- Content -->
<div id="content">
<!-- <h2 id="title">Log In</h2> -->
<form id="loginForm" method="post" action="config/config.index.php">
<input type="text" name="email" id="email" placeholder="Email">
<input type="password" name="password" id="password" placeholder="Password">
<input class="click" type="submit" name="submit" id="submit" value="Log in">
</form>
<p id="err"></p>
</div>
</div>
</body>
</html>
index.js
$(document).ready(function(){
$("#loginForm").submit(function(event){
event.preventDefault();
var email = $("#email").val();
var password = $("#password").val();
var submit = $("#submit").val();
$("#err").load("config/config.index.php",{
email: email,
password: password,
submit:submit
});
});
});
config.index.php
<?php
if(isset($_POST['submit'])){
$email = $_POST['email'];
$password = $_POST['password'];
$errEmptyAll = false;
$errEmptyEmail = false;
$errEmptyPassword = false;
$errEmail = false;
if(empty($email) && empty($password)){
echo 'Please enter an email and password.';
$errEmptyAll = true;
} else if(empty($email)){
echo 'Please enter an email.';
$errEmptyEmail = true;
} else if(empty($password)){
echo 'Please enter a password.';
$errEmptyPassword = true;
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo 'Please enter a valid email.';
$errEmail = true;
}
}
?>
<script>
var errEmptyAll = "<?php echo $errEmptyAll; ?>";
var errEmptyEmail = "<?php echo $errEmptyEmail; ?>";
var errEmptyPassword = "<?php echo $errEmptyPassword; ?>";
var errEmail = "<?php echo $errEmail; ?>";
if(errEmptyAll == true){
$("#email, #password").addClass("inputErr");
}
if(errEmptyEmail == true){
$("#email").addClass("inputErr");
}
if(errEmptyPassword == true){
$("#password").addClass("inputErr");
}
if(errEmail == true){
$("#email").addClass("inputErr");
}
</script>
The config PHP file should not have any JS at all.
Don't use .load(). Use $.ajax to send POST data and listen for server responses.
Build a json_encode response on PHP which will be returned to the browser via AJAX. Read the response data (from PHP) in JavaScript jQuery via the :success property or in the .done() method of $.ajax
index.html
<form id="loginForm" method="post" action="config/config.index.php">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit" name="submit">Log in</button>
</form>
<p id="err"></p>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script srrc="index.js"></script>
index.js
jQuery(($) => { // DOM ready and $ alias in scope
const $err = $("#err");
$("#loginForm").on("submit", function (ev) {
ev.preventDefault(); // prevent browser submit
$(this).find(`[name]`).removeClass("inputErr");
$.ajax({
type: "POST",
dataType: "JSON",
url: this.action, // from form action value
data: $(this).serialize(),
}).done((res) => {
// res is the JSON Response from PHP
console.log(res); // Do with this whatever you want. i.e:
if (res.errors.length) {
$err.text(res.errors.join(", "));
res.fields.forEach(field => {
$(`[name="${field}"]`).addClass("inputErr");
});
} else {
// SUCCESS!!!
}
});
});
});
config/config.index.php
<?php
$response = (object)[
"status" => "error",
"errors" => [],
"fields" => [], // IDs of fields with error
];
if (
$_SERVER["REQUEST_METHOD"] === "POST" &&
isset($_POST["email"]) &&
isset($_POST["password"])
) {
$email = $_POST["email"];
$password = $_POST["password"];
$passwordEmpty = empty($password);
$emailEmpty = empty($email);
$emailInvalid = !filter_var($email, FILTER_VALIDATE_EMAIL);
if ($passwordEmpty) :
$response->errors[] = "Invalid Password";
$response->fields[] = "password";
endif;
if ($emailEmpty) :
$response->errors[] = "Empty Email";
$response->fields[] = "email";
elseif ($emailInvalid) :
$response->errors[] = "Invalid Email";
$response->fields[] = "email";
endif;
if (empty($response->errors)) :
$response->status = "success";
endif;
}
echo json_encode($response);
exit;
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.
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);
?>
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.
I've spent some time looking on SO for an answer to this and have found some related issues, but nothing quite like mine...as usual....
I've got a fairly simple php/jquery ajax registration page that is working right up until the ajax callback. What I mean is the form data is passing to php and inserting into the db but when the php response is supposed to come back all that happens is the response displays in the browser. I've followed the logs, checked fiddler, re-written the code with/without json, and anothing seems to change. The odd thing is I have another form on a different page that is set up exactly the same way and everything works there perfectly. The only difference I can find between the two pages is the Request Headers of the php file. The one that works accepts json and the one the other one doesn't, but I have no idea if that means anything . . . I'm kind of grabbing for anything at this point.
So, without further delay, here is my code. Any thoughts/input are greatly appreciated. Thank you!
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="mobile.css" media="screen and (max-device-width: 480px)" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" media="screen and (min-width: 481px)" href="IEjoin.css" />
<![endif]-->
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="register.js" type="text/javascript"></script>
<script src="jquery.placeholder.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<div id="logo">
</div>
<div id="headline">
<h1>Create your account</h1>
</div>
<div id="container">
<form id="register" action="form.php" method="post">
<ul>
<li id="first_name">
<input name="fname" type="text" value="" id="fname" placeholder="First Name" maxlength="30">
<div class="error"></div>
</li>
<li id="last_name">
<input name="lname" type="text" value="" id="lname" placeholder="Last Name" maxlength="30">
<div class="error"></div>
</li>
<li id="email_address">
<input name="email" type="text" value="" id="email" placeholder="Email Address" maxlength="60">
<div class="error"></div>
</li>
<li id="uname">
<input name="username" type="text" value="" id="username" placeholder="Username" maxlength="15">
<div class="error"></div>
</li>
<li id="pword">
<input name="password" type="password" value="" id="password" placeholder="Password">
<div class="error"></div>
</li>
<li id="gender_select">
<select id="gender" name="gender">
<option value="" selected="selected">Select your gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="unspecified">Unspecified</option>
</select>
</li>
<li id="submit_button">
<button id="register_button" class="register_button_disabled">Create Account</button>
</li>
</ul>
</form>
<script> $('input[placeholder]').placeholder();</script>
</div>
</div>
</body>
$(document).ready(function() {
function validateEmail(email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email);
}
function submitButton() {
if (($("#first_name").hasClass("good")) && ($("#email_address").hasClass("good")) && ($("#uname").hasClass("good")) && ($("#pword").hasClass("good")) ){
$("#register_button").removeAttr("disabled");
$("#register_button").removeClass("register_button_disabled").addClass("register_button");
} else {
$("#register_button").attr("disabled", "disabled");
$("#register_button").removeClass("register_button").addClass("register_button_disabled");
}
}
$("body").mousedown(submitButton);
$("body").keyup(submitButton);
$("body").hover(submitButton);
$("body").mouseover(submitButton);
$("#fname").keydown(function(){
$("#first_name").removeClass("required");
$("#first_name div").html("");
});
$("#fname").bind ("keyup mousedown",function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("wait");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#fname").blur(function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#email").keydown(function(){
$("#email_address").removeClass("required");
$("#email_address div").html("");
});
$("#email").bind ("keyup mousedown",function(){
var email = this.value;
var emailLength = email.length;
if (emailLength<=4){
$("#email_address").removeClass("good").addClass("wait");
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#email").blur(function(){
var email = this.value;
var emailLength = email.length;
if ((emailLength<=4) || (!validateEmail(this.value))) {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (emailLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "Check.php",
data: "email="+email,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");}
else {
$("#email_address").removeClass("wait").addClass("good");
}
}
});
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#username").keydown(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("wait");
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#username").bind ("keyup mousedown",function(){
$("#uname").removeClass("required");
$("#uname div").html("");
});
$("#username").blur(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (unLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "check.php",
data: "username="+un,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
$("#uname").removeClass("wait").addClass("good");
}
}
});
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#password").keydown(function(){
var pw = this.value;
var pwLength = pw.length;
if(pwLength<=5){
$("#pword").removeClass("good").addClass("wait");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#password").bind ("keyup mousedown",function(){
$("#pword").removeClass("required");
$("#pword div").html("");
});
$("#password").blur(function(){
var pw = this.value;
var pwLength = pw.length;
if(pw===""){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please enter a password");
}
if(pwLength<=5){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please use at least 6 characters");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: "form.php",
data: $('#register').serialize(),
success: function(data) {
if (data === "fname") {
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else if (data === "email") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (data === "email2") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");
} else if (data === "username") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (data === "username2") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
window.location.href = "http://site.com";
},
error: function(httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
return false;
});
});
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$gender = mysql_real_escape_string($_POST['gender']);
//validate inputs
$emailpull = "SELECT email FROM $tbl_name WHERE email='$email'";
$emailresult=mysql_query($emailpull);
$emailnum=mysql_num_rows($emailresult);
$emailReg = "/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/";
$unpull = "SELECT username FROM $tbl_name WHERE username='$username'";
$unresult=mysql_query($unpull);
$unnum=mysql_num_rows($unresult);
if ($fname == "") {
$response = "fname";
} elseif ($email == "") {
$response = 'email';
} elseif (!preg_match($emailReg, $email)) {
$response = 'email';
} elseif ($emailnum > 0) {
$response = 'email2';
} elseif (strlen($username)<3) {
$response = 'username';
} elseif ($unnum > 0) {
$response = 'username2';
} elseif (strlen($password)<6) {
$response = 'password';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(fname,lname,email,username,password,gender)VALUES ('$fname','$lname','$email','$username','$password','$gender')";
}
$result=mysql_query($sql);
if($result)
$response = "success";
// send message back
echo $response;
?>
<?php
// close connection
mysql_close();
?>
The click handler for #button has this line which may be the culprit:
window.location.href = "http://crushonit.com";
This will redirect to that page when the form has no validation errors.