I am trying to setup a register box to create new account. I am trying to load the html form through ajax and passing data to a php file.
I want to make the div which is containing the form to reload every time when the "register" button is hit to get the result from the php script and display it out. However, my code seems not working properly (The ajax handling div will not load the form ). Below are my codes:
Register.php:
<?php
session_start();
$email = $_POST['email'];
$email = mysql_real_escape_string($email);
$pwd = $_POST['pwd'];
$repwd = $_POST['repwd'];
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$isValidEmail = 1;
if (substr_count($email, '#') != 1){
$isValidEmail = 0;
}
if($pwd != $repwd){ //check if password and re-entered passwords are the same
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Password and Re-entered Password are different.';
} else if( strlen($pwd) < 6 || strlen($pwd) > 64 ) { //check if password is 6 - 64 characters
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Password must be 6 - 64 characters.';
} else if( strlen($email) > 255) { //check if the email is too long
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Email exceeded maximum length.';
} else if ($isValidEmail != 1){
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Invalid Email.';
} else if (ctype_space($lname) || ctype_space($fname)){
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Please enter your name.';
} else {
if ($mysqli = new mysqli("localhost", "root", "", "my_db")){
$stmt = $mysqli->prepare("SELECT email FROM users WHERE email = ?");
$stmt->bind_param('s',$email);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
if ($result == $email) { //check if the input email exists in the database, duplicated user
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Email '.$email.' is already used.';
} else {
$hash = hash('sha256', $pwd);
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
$stmt = $mysqli->prepare("INSERT INTO users ( email, lastName, firstName, password, salt )
VALUES ( ? , ?, ?, ? ,? )");
$stmt->bind_param('sssss', $email, $lname, $fname, $hash, $salt);
if ($stmt->execute()){
$_SESSION['message'] = 'Registered.';
} else {
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Database query error occured.';
}
$stmt->close();
}
} else {
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Error connecting to the database.';
}
}
header("Location: Home.php");
$mysqli->close();
?>
ajax.js:
$(document).ready(function() {
$('#submit_register').click(function(){
$('#register_form').submit( function(){
$.ajax({
type: 'POST',
url : 'Register.php',
data: $('#register_form').serialize(),
success: function () {
var myURL = "Register_form.php#register_div";
$('#ajaxHandle').load(myURL);
return false;
},
});
});
});
});
Register_form.php:
<!DOCTYPE html>
<html lang="en">
<head>
<?php session_start(); ?>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="span-23 prepand-top last" id="register_div" style="background:gray;">
<div id="wrapper_register" class="span-21 last" style="padding-top: 20px; padding-left:20px; padding-bottom:20px;">
<form id="register_form" action="register.php" method="post">
<legend class="large">Register</legend>
<?php
if ($_SESSION['message']){
$class = "";
if ($_SESSION['error']){
$class = "error";
} else {
$class = "success";
}
echo "<div class=\"$class span-4 last\">";
echo $_SESSION['message'];
echo "</div>";
unset ($_SESSION['error']);
unset ($_SESSION['message']);
}
?>
<div class="span-23 prepand-top last">
<p>E-mail address: <br>
<input type="text" name="email" maxlength="255" /></p><br>
<p>Last Name: <br><input type="text" name="lname" maxlength="255" /></p><br>
<p>First Name: <br>
<input type="text" name="fname" maxlength="255" /></p><br>
<p>Password: <br>
<input type="password" name="pwd" /><p class="quiet">6 - 64 characters</p><br>
<p>Re-enter Password: <br><input type="password" name="repwd" /></p><br>
<input id="submit_register" type="submit" value="Register" /><br>
</div>
</form>
</div>
</div>
</body>
</html>
I am doing something wrong? Any advice will be appreciated. Thank you very much!
I think I figured it out. I have put the refreshing jquery code in the wrong place. It worked when I put it within the .submit scope:
$(document).ready(function() {
$('#submit_register').click(function(){
$('#register_form').submit( function(){
$.post(
'Register.php',
$(this).serialize()
);
var myURL = "Register_form.php#register_div";
$('#ajaxHandle').load(myURL);
return false;
});
});
});
Related
I have a login form that has two inputs email and password. If a user enters incorrect credentials, I have to show them the error. I have done form validation in PHP, so I need to send data from the form and get a response message without refreshing the page. I'm new to ajax, so I don't know how to do it
login.php
<form action="register.php" method="POST" autocomplete="off">
<h1 class="card-title display-4 mt-4 mb-5 text-center">Login</h1>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email" name="email" />
<div class="email-status"></div>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" placeholder="Password" name="password" />
<div class="password-status"></div>
</div>
<p class="card-text text-center">Forgot your password?</p>
<span class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary mb-4 w-50" style="border-radius: 20px;" name="login_btn" id="login_btn">Login</button>
</span>
<div class="success"></div>
</form>
<script>
$(document).ready(function() {
$("#login_btn").click(function() {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: 'register.php',
type: 'post',
data: {
email: email,
password: password
},
success: function(response) {
var emailstatus = "";
var passwordstatus = "";
var success = "";
if (response == 1) {
emailstatus = "required";
$(".email-status").text(emailstatus);
} else if (response == 2) {
emailstatus = "invalid";
$(".email-status").text(emailstatus);
} else if (response == 3) {
emailstatus = "match";
$(".email-status").text(emailstatus);
} else if (response == 4) {
passwordstatus = "required";
$(".password-status").text(passwordstatus);
} else if (response == 5) {
passwordstatus = "match";
$(".password-status").text(passwordstatus);
} else {
success = "sometihg went wrong";
$(".success").text(success);
}
}
});
});
});
</script>
register.php for form validation
if (isset($_POST['login_btn'])) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$new_password = md5($password);
$result = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email' OR password = '$new_password' LIMIT 1");
$row = mysqli_fetch_assoc($result);
//EMAIL
if (empty($email)) {
$email_status = "Email is required";
echo 1;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_status = "Enter valid Email ID";
echo 2;
} elseif ($row['email'] != $email) {
$email_status = "Email doesn't exist";
echo 3;
}
//PASSWORD
elseif (empty($password)) {
$password_status = "Password is required";
echo 4;
} elseif ($row['password'] != $new_password) {
$password_status = "Password doesn't match";
echo 5;
} else {
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$new_password'";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1) {
$rows = mysqli_fetch_array($results);
$_SESSION['username'] = $rows['username'];
$_SESSION['success'] = "You are now logged in";
if (isset($_SESSION['login_redirect'])) {
header("Location: " . $_SESSION["login_redirect"]);
unset($_SESSION["login_redirect"]);
} else if (isset($_SESSION['url'])) {
$url = $_SESSION['url'];
header("Location: $url");
} else {
header("Location: homepage.php");
}
exit;
} else {
$success = "Something went wrong";
echo 6;
}
}
}
If I run the above code, the page gets refresh and I'm not getting any response or validation messages
You have to prevent auto form submit. add an Id or a class to your form element and add this code
Inside of document ready
$("#form-id").submit(function(e){
e.preventDefault();
});
And in form element add an Id
<form action="register.php" id='form-id' method="POST" autocomplete="off">
Replace your data object of ajax as follows and your current code will work:
data: {
email: email,
password: password,
login_btn: true
}
You are checking isset of login_btn value which was not pass through the ajax.
I made a Signup form for my website. Then, I created PHP script which validates and insert user data into the database and it works perfectly. Then, I tried to make AJAX validation which will apply styles on the HTML elements and show error messages if an error occurs. I followed some tutorials, read answers and solutions from Stack Overflow, but for some reason, it doesn't work. When I click Submit button, nothing happens.
This is my code:
HTML
<form id="signupForm" action="./includes/signup.script.php" method="POST">
<div id="emptyFields" class="inputErrorMessage">
<p>You must fill all fields!</p>
</div>
<div class="form-group">
<label for="formGroupExampleInput">First name</label>
<input id="firstName" type="text" name="firstName" class="form-control formFieldBO">
<div id="firstNameChar" class="inputErrorMessage">
<p>First name must contain letters only.</p>
</div>
<div id="firstNameLength" class="inputErrorMessage">
<p>First name must contain at least 2 characters.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">Last name</label>
<input id="lastName" type="text" name="lastName" class="form-control formFieldBO">
<div id="lastNameChar" class="inputErrorMessage">
<p>Last name must contain letters only.</p>
</div>
<div id="lastNameLenght" class="inputErrorMessage">
<p>Last name must contain at least 2 characters.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">E-mail</label>
<input id="email" type="email" name="email" class="form-control formFieldBO">
<div id="emailValid" class="inputErrorMessage">
<p>Please, enter e-mail in valid form.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">Password</label>
<input id="password" type="password" name="password" class="form-control formFieldBO">
<div id="passwordChar" class="inputErrorMessage">
<p>Password must contain at least 6 characters.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">Confirm Password</label>
<input id="confirmPassword" type="password" name="confirmPassword" class="form-control formFieldBO">
<div id="passwordConfirm" class="inputErrorMessage">
<p>Confirmed password does not match.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">Country</label>
<select id="inputState" name="country" class="form-control formFieldBO">
<option value="" disabled selected>Select country</option>
<option value="AFG">Afghanistan</option>
</select>
<div id="countryChoose" class="inputErrorMessage">
<p>Please, choose your country.</p>
</div>
</div>
<div class="buttonBO">
<button type="submit" name="submit" class="btn btn-success">Submit</button>
</div>
</form>
JQuery script
$(document).ready(function() {
$("#signupForm").submit(function(event) {
event.preventDefault();
/*
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var email = $("#email").val();
var password = $("#password").val();
var confirmPassword = $("#confirmPassword").val();
var country = $("#inputState").val();
*/
var url = "includes/signup.script.php";
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: formData
});
});
});
PHP & JQuery
<?php
if (isset($_POST['submit']))
{
include_once "dbconn.script.php";
$firstName = mysqli_real_escape_string($conn, $_POST['firstName']);
$lastName = mysqli_real_escape_string($conn, $_POST['lastName']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$confirmPassword = mysqli_real_escape_string($conn, $_POST['confirmPassword']);
$user_role = 1;
$country = mysqli_real_escape_string($conn, $_POST['country']);
$errorEmpty = false;
$errorFirstNameChar = false;
$errorFirstNameNo = false;
$errorLastNameChar = false;
$errorLastNameNo = false;
$errorEmail = false;
$errorPasswordChar = false;
$errorPasswordMatch = false;
$errorCountry = false;
// Error handlers
// Check for empty fields
if (empty($firstName) || empty($lastName) || empty($email) || empty($password) || empty($confirmPassword))
{
header("Location: ../registration.php?registration=empty");
$errorEmpty = true;
exit();
}
else
{
// Check if input FIRST NAME characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $firstName))
{
header("Location: ../registration.php?registration=firstinvalidchar");
$errorFirstNameChar = true;
exit();
}
else
{
// Check if number of FIRST NAME characters is valid
if (strlen($firstName) < 2)
{
header("Location: ../registration.php?registration=invalid1");
$errorFirstNameNo = true;
exit();
}
else
{
// Check if input LAST NAME characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $lastName))
{
header("Location: ../registration.php?registration=lastinvalidchar");
$errorLastNameChar = true;
exit();
}
else
{
// Check if number of LAST NAME characters is valid
if (strlen($lastName) < 2)
{
header("Location: ../registration.php?registration=invalid2");
$errorLastNameNo = true;
exit();
}
else
{
// Check if EMAIL is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
header("Location: ../registration.php?registration=invalidemail");
$errorEmail = true;
exit();
}
else
{
// PREPARED STATEMENT
// Create template
$sql = "SELECT e_mail FROM hieroglyphicus_users WHERE e_mail=?;";
// Create prepared statement
$stmt = mysqli_stmt_init($conn);
// Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql))
{
echo "SQL statement failed!";
}
else
{
// Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "s", $email);
// Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0)
{
header("Location: ../registration.php?registration=userexists");
exit();
}
else
{
// Check if password number of characters is valid
if (strlen($password) < 6)
{
header("Location: ../registration.php?registration=invalidemaicharno");
$errorPasswordChar = true;
exit();
}
else
{
// Check if passwords match
if ($password != $confirmPassword)
{
header("Location: ../registration.php?registration=mismatchedpass");
$errorPasswordMatch = true;
exit();
}
else
{
if ($country == "")
{
header("Location: ../registration.php?registration=nocountry");
$errorCountry = true;
exit();
}
else
{
// Hashing passwords
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
// Insert a user into the database
// PREPARED STATEMENT
// Create template
$sql = "INSERT INTO hieroglyphicus_users (first_name, last_name, e_mail, user_pw, user_role, country)
VALUES (?, ?, ?, ?, ?, ?);";
// Create prepared statement
$stmt = mysqli_stmt_init($conn);
// Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql))
{
echo "SQL statement failed!";
}
else
{
// Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ssssis", $firstName, $lastName, $email, $hashedPwd, $user_role, $country);
// Run parameters inside database
mysqli_stmt_execute($stmt);
header("Location: ../registration.php?registration=success");
exit();
}
}
}
}
}
}
}
}
}
}
}
}
}
else
{
header("Location: ../registration.php");
exit();
}
?>
<script>
$("#firstName, #lastName, #email, #password, #confirmPassword, #country").removeClass("formFieldBOError").addClass("formFieldBO");
$(".inputErrorMessage").hide();
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorFirstNameChar = "<?php echo $errorNameFirstChar; ?>";
var errorFirstNameNo = "<?php echo $errorFirstNameNo; ?>";
var errorLastNameChar = "<?php echo $errorNameLastChar; ?>";
var errorLastNameNo = "<?php echo $errorLastNameNo; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var errorPasswordChar = "<?php echo $errorPasswordChar; ?>";
var errorPasswordMatch = "<?php echo $errorPasswordMatch; ?>";
var errorCountry = "<?php echo $errorCountry; ?>";
if (errorEmpty == true) {
$("#emptyFields").show();
$("#signupForm :input:not(:button):not(:select)").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorFirstNameChar == true) {
$("#firstNameChar").show();
$("#firstName").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorFirstNameNo == true) {
$("#firstNameChar").show();
$("#firstName").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorLastNameChar == true) {
$("#lastNameChar").show();
$("#lastName").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorLastNameNo == true) {
$("#lastNameChar").show();
$("#lastName").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorEmail == true) {
$("#emailValid").show();
$("#email").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorPasswordChar == true) {
$("#passwordChar").show();
$("#password").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorPasswordMatch == true) {
$("#passwordConfirm").show();
$("#confirmPassword").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorCountry == true) {
$("#countryChoose").show();
$("#inputState").removeClass("formFieldBO").addClass("formFieldBOError");
}
if (errorEmpty == false && errorFirstNameChar == false && errorFirstNameNo == false && errorLastNameChar == false && errorLastNameNo == false && errorEmail == false && errorPasswordChar == false && errorPasswordMatch == false && errorCountry == false) {
$("#firstName, #lastName, #email, #password, #confirmPassword, #country").val("");
}
</script>
I cannot spot the problem or error. Any help is highly appreciated!
$("#signupForm").on('submit', function(){
Put all the JQuery validation codes under this function .
Change button type="submit" to input type="submit" .
Let's see if this can solve your problems .
I am new to server mysql database, i just hosted my server with godaddy, connected to the database, my select query is working fine. After several trouble shooting i decided to use pdo transactions but am getting this error
My php registration script for insertion into database which is not working is show below:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors','1');
require_once('dbh.php');
require_once'config.php';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['f_name']) && isset($_POST['u_name']) && ($_POST['f_name']) !="" && ($_POST['u_name']) !="" && ($_POST['Email']) !="" && ($_POST['phonenumber']) !="" ) {
/* id should be an auto-increment field in the db */
$f_name = isset($_POST['f_name']) ? $_POST['f_name'] : false;
$u_name = isset($_POST['u_name']) ? $_POST['u_name'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$password1 = isset($_POST['password1']) ? $_POST['password1'] : false;
$Email = isset($_POST['Email']) ? $_POST['Email'] : false;
$phonenumber = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : false;
$sponsor = isset($_GET['sponsor']) ? $_GET['sponsor'] : false;
echo $sponsor;
$error_fname = "";
$eror_fname = "";
$errror_fname = "";
$eror_uname = "";
$errror_uname = "";
$error_uname = "";
$eror_password = "";
$errror_password = "";
$error_password = "";
$eror_email = "";
$error_email = "";
$errror_email = "";
$eror_phonenumber = "";
$error_phonenumber = "";
$errror_phonenumber = "";
$error_captcha = "";
$error_sponsor = "";
$errorSmt = "";
if(isset($_POST['f_name']) && isset($_POST['u_name']) && isset(($_POST['Email'])) && isset($_POST['phonenumber']) ) {
$errror_fname = $f_name.' is OK';
//check for duplicate username
$con= new PDO("mysql:host=$serverhost;dbname=silverhub;" , $serverusername, $serverpassword);
$query = $con->prepare("SELECT userid FROM users WHERE u_name=? LIMIT 1");
$u_Check = $query->bindParam(1, $u_name, PDO::PARAM_STR);
$u_Check = $query->execute();
$u_Check = $query->rowCount();
if( $u_Check=$query->rowCount() > 0) {
$eror_uname = ' Sorry'.$u_name.' already taken, please choose another';
}else{
$errror_uname = $u_name.' is OK';
}
//check for duplicate referral
$query = $con->prepare("SELECT sponsor FROM users WHERE userid=? LIMIT 1");
$s_Check = $query->bindParam(1, $userid, PDO::PARAM_INT);
$s_Check = $query->execute();
$s_Check= $query ->fetch(PDO::FETCH_ASSOC);
if( $s_Check['sponsor'] == $u_name) {
$error_sponsor = 'Sorry, user cannot refer himself';
}
//check referral Email
$query = $con->prepare("SELECT userid FROM users WHERE Email=? LIMIT 1");
$e_Check = $query->bindParam(1, $Email, PDO::PARAM_STR);
$e_Check = $query->execute();
$e_Check = $query->rowCount();
if( $p_Check=$query->rowCount() > 0) {
$eror_email = $Email.' already taken, please choose another';
}else{
$errror_email = $Email. ' is OK';
}
//check for duplicate phonenumber
$query = $con->prepare("SELECT userid FROM users WHERE phonenumber=? LIMIT 1");
$p_Check = $query->bindParam(1, $phonenumber, PDO::PARAM_STR);
$p_Check = $query->execute();
$p_Check = $query->rowCount();
if( $al_Check=$query->rowCount() > 0) {
$eror_phonenumber = $phonenumber.' already taken, please choose another';
}else{
$errror_phonenumber = $phonenumber. ' is OK';
}
}
// if(!preg_match("/^[a-zA-Z0-9]*$/",$f_name) && strip_tags(trim($f_name))) {
// $error_fname = 'invalid, fullname must be alphanumerics with no whitespace';
// echo 'invalid, fullname must be alphanumerics with no whitespace';
// }
if(!preg_match("/^[a-zA-Z0-9]*$/",$u_name) && strip_tags(trim($u_name))) {
$error_uname = 'invalid, username must be alphanumerics with no whitespace';
}
if(strlen($u_name) < 3 || strlen($u_name) > 16) {
$error_uname = 'Username must be between 3 - 16 characters';
}
if($password !== $password1) {
$error_password = 'Password and RepeatPassword do not match';
}
if(strlen($password) < 5) {
$error_password = 'Weak password, Password must be more than 5 characters';
}
if(strlen($phonenumber) > 11 && trim(htmlentities($phonenumber))) {
$error_phonenumber = 'Phonenumbers must be an 11 digit number';
}
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$error_email = ' invalid email address, please verify your email address';
}
if(!preg_match("/^[a-zA-Z0-9]*$/",$sponsor) && strip_tags(trim($sponsor))) {
$error_sponsor = 'invalid sponsor name, must be alphanumeric ';
}
if(empty($_POST['recaptcha'])) {
$error_captcha = 'Enter the Verification Code Above';
}
elseif($_POST['recaptcha'] != $_SESSION['recaptcha']) {
$error_captcha = 'Verification Code did not match, try again';
}elseif($_POST['recaptcha'] == $_SESSION['recaptcha']) {
$error_captcha = 'Verification Matched, Click Register';
}
if($u_name && $eror_fname =="" && $error_fname =="" && $errror_fname !=="" && $eror_uname =="" && $error_uname =="" && $errror_uname !=="" && $error_password =="" && $eror_email == "" && $error_email == "" && $errror_email !== "" && $eror_phonenumber =="" && $error_phonenumber =="" && $errror_phonenumber !=="" ) {
class reg extends dbh {
public function userCheck($f_name, $u_name,$password,$Email,$phonenumber,$sponsor) {
try {
$con = new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$con->beginTransaction();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$passenc = password_hash($password, PASSWORD_DEFAULT, array('cost'=>11));
$emailCode = rand().$phonenumber;
$smsCode = rand().$u_name;
$Active = 0;
$Has_reserved_person = 'NO';
$MainTime = time();
$con= new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$sql = "INSERT INTO users (f_name,u_name,password,Email,emailCode,phonenumber,smsCode,sponsor,Active,Has_reserved_person,MainTime) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
$insert = $con->prepare($sql);
$insert->bindParam(1,$f_name,PDO::PARAM_STR);
$insert->bindParam(2,$u_name,PDO::PARAM_STR);
$insert->bindParam(3,$passenc );
$insert->bindParam(4,$Email,PDO::PARAM_STR);
$insert->bindParam(5,$emailCode,PDO::PARAM_STR);
$insert->bindParam(6,$phonenumber,PDO::PARAM_STR);
$insert->bindParam(7,$smsCode,PDO::PARAM_STR);
$insert->bindParam(8,$sponsor,PDO::PARAM_STR);
$insert->bindParam(9,$Active);
$insert->bindParam(10,$Has_reserved_person);
$insert->bindParam(11,$MainTime);
$insert->execute();
$con->commit();
if($insert->execute()){
echo 'insert successfull';
}else{
echo "Execute query error, because:" . print_r($con->errorinfo());
return false;
}
} catch (PDOException $e){
throw $e;
}
}
}
$object = new reg();
$object->userCheck( $f_name, $u_name, $password, $Email, $phonenumber, $sponsor);
}
}
?>
Here is my HTML FORM input:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html !doctype>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div id="container">
<div id="sec">REGISTER WITH US</div>
<img src="images/images(33).jpg">
<form action='register.php' method='POST' class='ajax-reg'>
<!-- HOW does a user enter a value here if it is HIDDEN??? Removed `required` attribute -->
<div class='form-group'>
<p> Note!!! Fields with astericks must be filled</p>
<input type='hidden' class='form-control' name='userid' placeholder='enter your id' />
</div>
<br>
<div class='form-group'>
<label>fullname*</label>
<input type="text" class="form-control" onblur ="fnamecheck()" id="f_name" name="f_name" placeholder="Enter your fullname" value="<?php echo #$_POST['f_name']?>" /><span id ="fullnameStatus"></span>
</div>
<br>
<div class='form-group'>
<label>username*</label>
<input type="username" class="form-control" name="u_name" id ="u_name" onblur ="usernamecheck()" placeholder="Enter your username" value="<?php echo #$_POST['u_name']?>" /><span id ="usernameStatus"></span>
</div>
<br>
<div class='form-group' >
<label>password*</label>
<input type="password" class="form-control" name="password" id="password" onblur ="passcheck()" placeholder="type in your password" />
</div>
<br>
<div class='form-group' >
<label>RepeatPassword*</label>
<input type="password" class="form-control" name="password1" id ="password1" onblur ="passcheck()" placeholder= "Retype in your password" /><span id ="passwordStatus"></span>
</div>
<br>
<div class='form-group'>
<label>email*</label>
<input type="email" class="form-control" name="Email" id ="Email" onblur ="emailcheck()" placeholder="Enter your email" value="<?php echo #$_POST['Email']?>" /><span id ="emailStatus"></span>
</div>
<br>
<div class='form-group'>
<label>phonenumber*</label>
<input type="number" class="form-control" name="phonenumber" id = "phonenumber" onblur ="phcheck()" placeholder="Enter your phonenumber" value="<?php echo #$_POST['phonenumber']?>" /><span id ="phonenumberStatus"></span>
</div>
<br>
<div>
<?php if (isset($_GET['sponsor']) && $_GET['sponsor'] != "") {?>
<input type="hidden" class="form-control" name="sponsor" id ="sponsor" onblur ="usernamecheck()" placeholder="type in your sponsor username here" value="<?php $sponsor = $_GET['sponsor'];?>" />
<?php }?>
</div>
<br>
<div id="captcha"><img src="captcha.php"></div>
<br>
<div id="refresh"><p> Refresh To Change Code</p></div>
<div id="captcha">
<input type="text" class="form-control" name="recaptcha" id = "recaptcha" onblur ="recaptchacheck()" placeholder="Enter The Code Above" /><span><?php echo #$error_captcha?></span><span id ="recaptchaStatus"></span>
</div>
<div class='form-group'>
<!-- this checkbox needs a name!! Assign name `terms` -->
<input type="checkbox" name="terms" required />
</div>
<div id="terms"> </a><a href="terms.php" >I agree with terms and conditions</a></div>
<div>
<input type='submit' class='btn btn-success' name='submit_signup' value='REGISTER' />
</div>
<br>
</form>
<br>
<div></div>
</div>
<footer>
</footer>
<script lang="javascript" type="text/javascript" src="jqueryfunctions.js"></script>
<script lang="javascript" type="text/javascript" src="ajaxfiles.js">
</script>
</body>
</html>
When I run this code below, the "data" returned is an empty string "[]". (At least viewed through the Chrome Console Viewer)
If I comment out the "event.preventDefault();" line in the JS I get a page reload, as expected, and a JSON string with results that passes JSONLint. I know the PHP is working as I am getting new inserts into the mySQL database and the return values make sense.
Everything seems to run correctly even with "data" is returned empty... (i.e. I am getting the console.log of FIRST first and SECOND second followed by the empty string.) I just can't get the returned "data" values in the JS context.
I'm kinda new to web development, not to programming... but does anyone spot a rookie mistake? I have read over about 12 similar questions and tried many things, but nothing is helping...
Thanks in advance.
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'firstName': $('input[name=firstName]').val(),
'lastName': $('input[name=lastName]').val(),
'email': $('input[name=email]').val(),
'password': $('input[name=password]').val()
};
$.ajax({
type: 'POST',
url: 'createaccount.php',
data: formData,
dataType: 'json'
})
.done(function(data) {
console.log("SECOND");
console.log(data);
});
console.log("FIRST");
event.preventDefault();
});
});
input {
border-radius: 5px;
border-width: 1px;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-12 text-center">
<div class="col-lg-4"></div>
<div class="col-lg-4 text-right">
<h1>Join website</h1>
<form action="createaccount.php" method="post">
<label>First Name:</label><input type="text" name="firstName" /><br/>
<label>Last Name:</label><input type="text" name="lastName" /><br/>
<label>Email:</Label><input type="email" name="email" /><br/>
<label>Password:</label><input type="password" name="password" /><br/>
<input type="submit" value="Sign Up" name="submit" />
</form>
</div>
<div class="col-lg-4"></div>
</div>
</div>
<?php
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$email = $_POST["email"];
$password = $_POST["password"];
$submit = $_POST["submit"];
$errors = array();
$data = array();
if ($submit) {
if (!$email) {
$errors['email'] = "Email is required.";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['validemail'] = "Valid email is required.";
}
if (!$password) {
$errors['password'] = "Password is required.";
}
else {
if (strlen($password) < 8) {
$errors['passwordlength'] = "Password must be at least 8 characters long";
}
if (!preg_match("#[A-Z]+#", $password)) {
$errors['passwordcaps'] = "Password must contain at least one Capital Letter";
}
}
if (empty($errors)) {
require 'dbconnect.php';
$query="SELECT * FROM Users WHERE email='".mysqli_real_escape_string($link, $email)."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$errors['exists'] = "That email address is already registered.";
}
else {
$firstName = mysqli_real_escape_string($link, $firstName);
$lastName = mysqli_real_escape_string($link, $lastName);
$email = mysqli_real_escape_string($link, $email);
$password = md5(md5($email).$password);
$query="INSERT INTO `Users` (`FirstName`, `LastName`, `Email`, `Password`, `IsRater`, `IsRatee`) VALUES('$firstName', '$lastName', '$email', '$password', '1', '1');";
if(!mysqli_query($link, $query)) {
$errors['SQLQuery'] = "Failed SQL Insert" . mysqli_error($link);
}
else
{
$data['success'] = true;
$data['message'] = 'Your account has been created!';
}
}
}
if(!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
The PHP code checks whether $_POST['submit'] is set before doing anything with the form data, but you never set that in formData. Try:
var formData = {
'firstName': $('input[name=firstName]').val(),
'lastName': $('input[name=lastName]').val(),
'email': $('input[name=email]').val(),
'password': $('input[name=password]').val(),
'submit': 'on'
};
Okay.. so to start off I only have Php 5.3 so I can't use bcrypt, I am not familiar with salt but an completely willing to do it if someone can help me out. I also would like to know if this script is bad or good for sql injections. My biggest problems is when I use something like crypt and try to get my passwords to match, it won't. I've been working on this for days and can't seem to find the right solution to my problem. the code is not done yet, but its able to run. I'm just doing this on wamp so i dunno if thats a problem? but i cant imagine it is.
REGISTER . PHP
if ((strlen($username)) < 6 || (preg_match("/[^\w-.]/", $username)) ) {
header('Location: Register.php?fail=1');
die();
}
if ((strlen($password)) < 8) {
header('Location: Register.php?fail=2');
die();
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header('Location: Register.php?fail=3');
die();
}
/*
TRIED METHODS
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt('rasmuslerdorf', '$2y$10$'.$salt.'$');
$password = $hash;
echo "<script>alert('$password');</script>";
$salt = '$2a$07$usesomadasdsadsadsadasdasdasdsadesillystringfors';
$digest = crypt($password, $salt);
if (crypt($password, $digest) == $digest){
echo "<script>alert('logged in');</script>";
}else{
header('Location: Login.php?fail=3');
die();
}
*/
//PDO CONNECTION
function pdo_connect() {
try {
$db = new PDO("mysql:host=localhost;dbname=XXX", "XXX", "XXX");
return $db;
} catch (PDOException $e) {
//echo $e->getMessage();
//return false;
header('Location: Register.php?fail=6');
}
}
//CHECK IF USERNAME EXISTS
function usernameCheck($username) {
$con = pdo_connect();
$ustmt = $con->prepare("SELECT u_users FROM users WHERE u_users = :name");
$ustmt->bindParam(':name', $username);
$ustmt->execute();
if($ustmt->rowCount() > 0){
header('Location: Register.php?fail=4');
die();
}
$con = null;
}
echo usernameCheck($username);
//CHECK IF EMAIL EXISTS
function emailCheck($email) {
$con = pdo_connect();
$estmt = $con->prepare("SELECT u_email FROM users WHERE u_email = :name");
$estmt->bindParam(':name', $email);
$estmt->execute();
if($estmt->rowCount() > 0){
header('Location: Register.php?fail=5');
die();
}
$con = null;
}
echo emailCheck($email);
//INSERT EMAIL TO NEWSLETTER
function emailnewsletterCheck($email) {
$con = pdo_connect();
$nstmt = $con->prepare("SELECT n_email FROM newsletter WHERE n_email = :email");
$nstmt->bindParam(':email', $email);
$nstmt->execute();
if($nstmt->rowCount() < 1){
$addstmt = $con->prepare('INSERT INTO newsletter (n_email) VALUES (:email)');
$addstmt->bindParam(':email', $email);
$addstmt->execute();
}
$con = null;
}
echo emailnewsletterCheck($email);
//INSERT
function insert($username,$password,$email,$type) {
$con = pdo_connect();
$password = md5($password);
$istmt = $con->prepare('INSERT INTO users (u_users, u_private, u_email, u_type) VALUES (:username, :password, :email, :type)');
$istmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':type' => $type
));
$con = null;
header('Location: Login.php?success=1');
}
echo insert($username,$password,$email,$type);
}//end submit
?>
<?php
$page_title = "NS : Web Development : Register";
$page_desc = "Register with us for great deals on website development.";
$services = 0;
include_once 'header.php';
?>
<script type="text/javascript">
// This function checks if the username field is at least 6 characters long.
function checkUsernameForLength(whatYouTyped) {
var fieldset = whatYouTyped.parentNode.parentNode.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 5) {
$("span.hint").hide();
}
}
// If the password is at least 4 characters long
function checkPassword(whatYouTyped) {
var fieldset = whatYouTyped.parentNode.parentNode.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 7) {
$("span.hint").hide();
}
}
// This function checks the email address blah#blah.blah
function checkEmail(whatYouTyped) {
var fieldset = whatYouTyped.parentNode.parentNode.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt)) {
$("span.hint").hide();
}
}
// this part is for the form field hints to display
// only on the condition that the text input has focus.otherwise, it stays hidden.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function prepareInputsForHints() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++){
inputs[i].onfocus = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
</script>
<div class="jumbotron">
<div class="container">
<h1>Register for <font color="fb1576">great</font> opportunities</h1>
<p>Get full quotes, package <font color="fb1576">deals</font>, news and updates on the latest themes and scripts, and even <font color="fb1576">win</font> free prizes<font color="fb1576">!</font>
</div>
</div>
<div class="container">
<!-- row of columns -->
<div class="row">
<?php
if ( isset($_GET['fail']) && $_GET['fail'] == 1 ){
echo "<div class='alert alert-danger'>Username must be at least 6 characters in length and can only contain characters matching (a-z) (A-Z) (0-9) and '_' Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 2 ){
echo "<div class='alert alert-danger'>Password must be at least 8 characters in length and cannot exceed 25. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 3 ){
echo "<div class='alert alert-danger'>E-mail is not valid. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 4 ){
echo "<div class='alert alert-danger'>Username you chose already exists. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 5 ){
echo "<div class='alert alert-danger'>E-mail you entered is already in use. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 6 ){
echo "<div class='alert alert-danger'>Something went wrong, we couldn't submit your registration. Please try again later. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
?>
<form name="basicform" id="basicform" method="POST">
<fieldset>
<div class="input-group">
<label for="username">Choose a Username:</label><br>
<input type="text" id="username" name="username" onkeyup="checkUsernameForLength(this);" required class="form-control" maxlength="25" pattern=".{6,}"/>
<span class="hint">Usernames must be a least 6 characters in length and cannot exceed 25. Characters must match (a-z) (A-Z) (0-9) and '_'</span>
</div>
</fieldset>
<fieldset>
<div class="input-group">
<label for="password">Enter a password:</label><br>
<input type="password" id="password" name="password" onkeyup="checkPassword(this);" required class="form-control" maxlength="25" pattern=".{7,}"/>
<span class="hint">The password can be any combination of <strong>characters</strong>, and must be at least 8 characters in length and cannot exceed 25.</span>
</div>
</fieldset>
<fieldset>
<div class="input-group">
<label for="email">Enter your email address:</label><br>
<input type="text" id="email" name="email" onkeyup="checkEmail(this);" required class="form-control" maxlength="30" />
<span class="hint">Please enter your real email address (ie: you#emailprovider.com)</span>
</div>
</fieldset>
<fieldset>
<label for="type">Pick your position of registration:</label><br>
<select name="type">
<option name="type" value="Client">I am a client looking for work to be done</option>
<option name="type" value="Employer">I am an employer looking for a potential hire</option>
<option name="type" value="Employee">I am an employee looking to be hired</option>
</select>
</fieldset>
<fieldset>
<button type="submit" class="btn btn-primary" name="submit" value="submit">Register Now</button>
</fieldset>
</form>
</div>
<!-- //row of columns -->
<?php
include_once 'footer.php';
?>
LOGIN . PHP
$username = $_POST['username'];
$password = $_POST['password'];
//before we even bother connecting to the db start validating
if ( (empty($username)) || (empty($password)) ) {
header('Location: Login.php?fail=1');
die();
}
if ( ((strlen($username)) >25) || ((strlen($password)) >25) ) {
header('Location: Login.php?fail=2');
die();
}
if ( (preg_match("/[^\w-.]/", $username)) ) {
header('Location: Login.php?fail=3');
die();
}
/*
TRIED METHODS
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt('rasmuslerdorf', '$2y$10$'.$salt.'$');
$password = $hash;
echo "<script>alert('$password');</script>";
$salt = '$2a$07$usesomadasdsadsadsadasdasdasdsadesillystringfors';
$digest = crypt($password, $salt);
if (crypt($password, $digest) == $digest){
echo "<script>alert('logged in');</script>";
}else{
header('Location: Login.php?fail=3');
die();
}
*/
//PDO CONNECTION
function pdo_connect() {
try {
$db = new PDO("mysql:host=localhost;dbname=XXX", "XXX", "XXX");
return $db;
} catch (PDOException $e) {
//echo $e->getMessage();
//return false;
header('Location: Register.php?fail=6');
}
}
//CHECK IF USERNAME EXISTS
function checkLogin($username,$password) {
$con = pdo_connect();
//$getlogin = $con->query
$getlogin = $con->prepare("SELECT u_users,u_private FROM users WHERE u_users = :username AND u_private = :password");
$getlogin->bindValue(':username', $username, PDO::PARAM_STR);
$getlogin->bindValue(':password', $password, PDO::PARAM_STR);
$getlogin->execute();
if($getlogin->rowCount() > 0){
echo "<script>alert('yes');</script>";
}
$con = null;
}
echo checkLogin($username,$password);
echo "<script>alert('success');</script>";
}
?>
<?php
$page_title = "NS : Web Development : Register";
$page_desc = "Register with us for great deals on website development.";
$services = 0;
include_once 'header.php';
?>
<div class="jumbotron">
<div class="container">
<h1><font color="fb1576">Members</font> log in</h1>
<p> Not yet a member? <font color="fb1576">Sign up today!</font>
</div>
</div>
<div class="container">
<?php
if ( isset($_GET['success']) && $_GET['success'] == 1 ){
echo "<div class='alert alert-success'>Registration successful. Please log in.</div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 1 ){
echo "<div class='alert alert-danger'>Username or Password cannot be left blank.</div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 2 ){
echo "<div class='alert alert-danger'>Sorry, this is not a valid Username or Password.</div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 3 ){
echo "<div class='alert alert-danger'>Username or Password incorrect, please try again.</div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 5 ){
echo "<div class='alert alert-danger'>E-mail you entered is already in use. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 6 ){
echo "<div class='alert alert-danger'>Something went wrong. Please try again later. </div>";
}
?>
<form class="form-signin" role="form" method="POST">
<h2 class="form-signin-heading">Please sign in</h2>
<p>
<input type="text" class="form-control" placeholder="Username" name="username" required autofocus>
</p>
<br>
<p>
<input type="password" class="form-control" placeholder="Password" name="password" required>
</p>
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="submit" value="submit">Sign in</button>
</form>
<?php
include_once 'footer.php';
?>
I REALLLLLYY need to get it so it is secure for my server on launch and can login a user safely.
With PHP version 5.3 you can and should use BCrypt.
For PHP version 5.5 and higher it is recommended to use the new password functions password_hash() and password_verify():
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
For PHP version 5.3.7 and higher there exists a compatibility pack, so you can use the functions above in exactly the same way.
For PHP versions earlier than 5.3.7 you could use the compatibility pack and change the crypt parameter from "$2y$%02d$" to "$2a$%02d$", this generates a BCrypt hash as well. It is the best you can do with older versions, the hashes will be compatible when you update to a newer PHP version.
When you want to verify the password, you cannot do this in the SQL statement directly. In a first step you have to get the stored password-hash from the database (with the username), then you can use this hash in the function password_verify(). The password_verify() function needs to extract the salt from the stored hash.