I am using JQuery to check if username is in use, however I have some issues. It is always stuck of "Searching". Image below shows exactly what the issue is.
Register.JS:
$(document).ready(function(){
$('#username').keyup(function() {
var username = $(this).val();
$('#usernameCheck').text('Searching...');
if (username === '') {
$('#usernameCheck').text('');
}else {
$.post('usernamecheck', { username:username }, function(data) {
$('#usernameCheck').text(data);
});
}
});
});
Register.php:
<html>
<head>
<title>Register</title>
<link rel='stylesheet' type='text/css' href='styles.css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="JS/register.js"></script>
</head>
</html>
<?php
echo '<form action="register.php?action=registerCheck" method="post" name="formOne">
<br/><input type="text" id="username" placeholder="Username" maxlength="50" title="Maximum 50 charcters or less."><span id="usernameCheck"></span><br/>
<br/><input type="password" name="passwordOne" placeholder="Password" maxlength="60" title="Maximum 60 charcters or less."><br/>
<br/><input type="password" name="passwordTwo" placeholder="Retype Password" maxlength="60" title="Must be the same as the password field above this."><br/>
<br/><input type="text" name="email" placeholder="Email Address" title="Must be correct in-case admins wish to contact you."><br/>
<br/><textarea disabled rows="1" cols="4" name="defSpamCheck">'.$spamCheck.'</textarea><br/>
<br/><textarea rows="1" cols="30" name="userSpamCheck" placeholder="Enter the 4 digit code above." title="Needed to check for bots."></textarea><br/>
<br/><input type="submit" value="Register" onclick="return validate()">
</form>';
}
function registerCheck() {
global $PDO;
// All the validations
if (!isset($_POST['username']) || empty($_POST['username'])) {
echo '<br/>';
echo '<p class="error">You missed out the usernane field.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['passwordOne']) || empty ($_POST['passwordOne'])) {
echo '<br/>';
echo '<p class="error">You missed out the password field.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['passwordTwo']) || empty ($_POST['passwordTwo'])) {
echo '<br/>';
echo '<p class="error">You missed out the second password field.</p>';
echo 'Back';
endPage();
} else if ($_POST['passwordOne'] != $_POST['passwordTwo']) {
echo '<br/>';
echo '<p class="error">Passwords do not match.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['email']) || empty ($_POST['email'])) {
echo '<br/>';
echo '<p class="error">You missed out the email field.</p>';
echo 'Back';
endPage();
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo '<br/>';
echo '<p class="error">Email not valid.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['userSpamCheck']) || empty ($_POST['userSpamCheck'])) {
echo '<br/>';
echo '<p class="error">You missed out the spam check field.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['username']) > 50) {
echo '<br/>';
echo '<p class="error">Username has to be 50 characters or less.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['passwordOne']) && strlen($_POST['passwordTwo']) > 60) {
echo '<br/>';
echo '<p class="error">Password has to be 60 characters or less.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['username']) < 5) {
echo '<br/>';
echo '<p class="error">Username has to be greater than 5 characters.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['passwordOne']) && strlen($_POST['passwordTwo']) < 5) {
echo '<br/>';
echo '<p class="error">Password has to be greater than 5 characters</p>';
echo 'Back';
endPage();
} else {
$username = htmlspecialchars($_POST['username']);
// Replace all these with $replace
$sChars = array ("<", ">", "(", ")", "*", "&", "#", ":");
$replace = ' ';
// Trim to remove any blank spaces
trim(str_replace($sChars, $replace, $username));
$password = sha1(htmlspecialchars($_POST['passwordOne']));
$email = htmlspecialchars($_POST['email']);
$stmtOne = $PDO->prepare("SELECT COUNT(`uID`) uUsername FROM `users` WHERE uUsername=? LIMIT 1");
$stmtOne->bindParam(1, $username, PDO::PARAM_INT);
$stmtOne->execute();
$result = $stmtOne->fetch(PDO::FETCH_ASSOC);
if ($result == 1) {
echo '<br/>';
echo '<p class="error">Username already in use, pick another one.</p>';
echo 'Back';
endPage();
}
$stmtTwo = $PDO->prepare("INSERT INTO `users` (uUsername, uPassword, uEmail) VALUES (?, ?, ?)");
if ($stmtTwo->execute(array($username, $password, $email))) {
echo '<br/>';
echo '<p class="norm">Account created! You can now log in.</p>';
header("Refresh:3; URL=login.php");
endPage();
} else {
echo '<br/>';
echo '<p class="error">We could not create your account, please try again later.</p>';
header("Refresh:3; URL=login.php");
endPage();
}
}
}
?>
usernamecheck.php:
<?php
include 'pdo.config.php';
include 'register.php';
global $username;
$stmtOne = $PDO->query("SELECT COUNT(*) uUsername FROM `users` WHERE uUsername='$username'");
$rows = $stmtOne->fetchALL();
$count = count($rows);
if ($count < 1) {
echo 'Username already in use, pick another one';
} else if ($count == 0) {
echo 'Username available';
}
?>
But it won't work, what am I doing wrong?
$count is the number of rows. Your query always returns exactly 1 row, since it's just returning a count. Also, both your if tests are checking if $count is 0 (I think you meant to write $count == 1 for the first one).
$stmtOne = $PDO->prepare("SELECT COUNT(*) uUsername FROM `users` WHERE uUsername = :username");
$stmtOne->exec(array('username' => $username));
$row = $stmtOne->fetch(PDO::FETCH_OBJ);
$count = $row->uUsername;
if ($count == 1) {
echo 'Username already in use, pick another one';
} else if ($count == 0) {
echo 'Username available';
}
Okay, so my code was right but I had a small but critical error.
$(document).ready(function(){
$('#username').keyup(function() {
var username = $(this).val();
$('#usernameCheck').text('Searching...');
if (username === '') {
$('#usernameCheck').text('');
}else {
$.post('usernamecheck', { username:username }, function(data) {
$('#usernameCheck').text(data);
});
}
});
});
Where it's looking for the file, I put "usernamecheck". It was mean't to be usernamecheck.php. I missed out the file extension.
Related
Im currently learning my way with ajax. Im trying to make a register / login system with AJAX. I finished the register form and is now working but im having problems with the login one.
ajax/login.php PHP Vaidation for Login
<?php
require_once("../core/config.php");
$username = trim(strip_tags($_POST['username']));
$password= trim(strip_tags($_POST['password']));
$errors = false;
$user_query = $db->query("SELECT * FROM users WHERE username='$username'");
// Empty check -> Username
if(empty($username) && strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) && strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }
// If exists check
$num = $user_query->num_rows;
if($num < 1) { $error_general = "<span style='color:red;'> User doesn't exist </span>"; $errors = true; } else {
$user = $user_query->fetch_object();
if($user->password != $password) { $error_general = "<span style='color:red;'> Invalid Username or Password </span>"; $errors = true; }
}
//
if($errors == true) {
?>
<?php if(isset($error_general)) { echo $error_general." <br><br>"; } ?>
<?php if(isset($error_username)) { echo $error_username; } ?>
<input type="text" name="login_username" id="login_username" placeholder="Username" value="<?php echo $username; ?>"> <br>
<?php if(isset($error_password)) { echo $error_password; } ?>
<input type="password" name="login_password" id="login_password" placeholder="Password" value="<?php echo $password; ?>">
<br>
<?php } else {
$_SESSION['User'] = true;
header("Location: ". $_SERVER['PHP_SELF']);
}
?>
index.php Form HTML & JS
<!DOCTYPE HTML>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
var loader = $("<div style='text-align: center; float:none; margin: 0 auto;'> <img src='loader-small.gif'> <br> Processing request... </div> <br>");
function process_login() {
var username = $("#login_username").val();
var password =$("#login_password").val();
$(".login_container").html(loader).load("ajax/login.php", {username: username, password: password})
}
</script>
</head>
<body>
<h3> Login </h3>
<form action="" method="POST">
<div class="login_container">
<input type="text" name="login_register" id="login_username" placeholder="Username"> <br>
<input type="password" name="login_password" id="login_password" placeholder="Password">
<br>
</div>
<input type="submit" onclick="process_login(); return false;" name="login_submit" value="Login" style="outline:none;">
</form>
</body>
</html>
When I submit the form with the correct information I get "User doesnt exist", "Username is empty", "Password is empty" and when I submit with wrong information I get "User doesnt exist"
I've been brainstorming for the last 3 hours, yet I have not found a way to fix it
Logical error:
// Empty check -> Username
if(empty($username) || strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) || strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }
Compare to you code:
// Empty check -> Username
if(empty($username) && strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) && strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }
So I have created a PHP validation script. On test I filled and submitted the forms but so far $error returns undefined index and no data is set into the database. Can anyone take a look and give a second opinion on why its not functioning as intended? To my eye it all looks OK.
Otherwise my script runs OK (Insert into DB) it's just something about my validation script breaks it.
<?php
if (isset($_POST['Submit'])) {
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter a name.<br/>';
}
if (isset($_POST['Submit'])) {
if ($_POST['address'] != "") {
$_POST['address'] = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
if ($_POST['address'] == "") {
$errors .= 'Please enter a valid address<br/><br/>';
}
} else {
$errors .= 'Please enter a address.<br/>';
}
if (isset($_POST['postcode'])) {
if ($_POST['postcode'] != "") {
$_POST['postcode'] = filter_var($_POST['postcode'], FILTER_SANITIZE_STRING);
if ($_POST['postcode'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter a name.<br/>';
}
if (!$errors) {
$name = $_POST['name'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$photo = $_POST['photo'];
$db1 = new dbmember();
$db1->openDB();
$numofrows = $db1->insert_member('', $name, $address, $postcode, $photo);
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
$sql="SELECT * from member";
$result=$db1->getResult($sql);
echo "<table class='table table-hover'>";
echo "<tr><th>Member ID</th><th>Name</th><th>Address</th><th>Postcode</th><th>Photo</th></tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>{$row['mid']}</td><td>{$row['name']}</td>";
echo "<td>{$row['address']}";
echo "<td>{$row['postcode']}";
echo"<td><img height='80' width='120' src='{$row['photo'] }' /></td>";
echo "</tr>";
}
echo "</table>";
$db1->closeDB();
}
}
}
}
echo "Records updated!<br/><br/>";
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" name="myform" class = "well" id="myform" onsubmit="return validateForm( );">
Please fill in the fields to add a new member
<p></p>
<input type="text" class="span3" placeholder="Enter member name"name="name" id="name" /><br />
<input type="text" class="span3"placeholder="Enter an address"name="address" id="address" /><br />
<input type="text" class="span3"placeholder="Enter a postcode"name="postcode" id="postcode" /><br />
<input type="text"class="span3" placeholder="Enter a picture (optional)"name="photo" /><br />
<p>
<button class="btn btn-primary" type="submit" value="Save" >Submit </button>
</p>
</form>
Your button doesn't have a name="Submit" attribute. Your php code can't find the $_POST['Submit'] because it doesn't exist.
Consequently, the if (isset($_POST['Submit'])) { condition will return false meaning the validation is never performed and the $error variable never set to a value.
I have a problem with php & mysql, insert to database using utf-8.
first file:
addsite:
<?php
include 'header.php';
if(isset($data)) {
foreach($_POST as $key => $value) {
$posts[$key] = filter($value);
}
if(isset($posts['type'])){
if($posts['url'] == "http://" || $posts['url'] == ""){
$error = "Add your page link!";
}else if($posts['title'] == ""){
$error = "Add your page title!";
}else if(!preg_match("/\bhttp\b/i", $posts['url'])){
$error = "URL must contain http://";
}else if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $posts['url'])){
$error = "Please do not use special characters in the url.<";
}else{
include "plugins/" . $posts['type'] . "/addsite.php";
}
}
?>
<div class="contentbox">
<font size="2">
<li>Pick the type of exchange you are promoting from the dropdown menu.</li>
<li>Set the amount of coins you wish to give per user complete(CPC).</li>
<li>The higher the amount of coins the higher the Links position.</li>
</div>
<div class="contentbox">
<div class="head">Add Site</div>
<div class="contentinside">
<?php if(isset($error)) { ?>
<div class="error">ERROR: <?php echo $error; ?></div>
<?php }
if(isset($success)) { ?>
<div class="success">SUCCESS: <?php echo $success; ?></div>
<?php }
if(isset($warning)) { ?>
<div class="warning">WARNING: <?php echo $warning; ?></div>
<?php } ?>
<form class="contentform" method="post">
Type<br/>
<select name="type"><?php $select = hook_filter('add_site_select', ""); echo $select; ?></select><br/><br/>
Link<br/>
<input name="url" type="text" value="<?php if(isset($posts["url"])) { echo $posts["url"]; } ?>"/><br/><br/>
Title<br/>
<input name="title" type="text" value="<?php if(isset($posts["title"])) { echo $posts["title"]; } ?>"/><br/><br/>
Cost Per Click<br/>
<?php if($data->premium > 0) { ?>
<select name="cpc"><?php for($x = 2; $x <= $site->premcpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php }else{ ?>
<select name="cpc"><?php for($x = 2; $x <= $site->cpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php } ?>
<input style="width:40%;" type="Submit"/>
</form>
</div>
</div>
<?php
}
else
{
echo "Please login to view this page!";
}
include 'footer.php';
?>
second file , plugin addsite.php
<?php
$num1 = mysql_query("SELECT * FROM `facebook` WHERE `url`='{$posts['url']}'");
$num = mysql_num_rows($num1);
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'facebook.com')) {
$error = "Incorrect URL! You must include 'facebook.com'";
}else{
mysql_query($qry);
mysql_query("INSERT INTO `facebook` (user, url, title, cpc) VALUES('{$data->id}', '{$posts['url']}', '{$posts['title']}', '{$posts['cpc']}') ");
$success = "Page added successfully!";
}
?>
when i write arabic language in the form and submit ,
it went to database with unkown language like :
أسÙ
database collaction : utf8_general_ci
config file
$host = "localhost"; // your mysql server address
$user = ""; // your mysql username
$pass = ""; // your mysql password
$tablename = ""; // your mysql table
session_start();
$data = null;
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
include_once 'functions.php';
require_once "includes/pluggable.php";
foreach( glob("plugins/*/index.php") as $plugin) {
require_once($plugin);
}
hook_action('initialize');
$site = mysql_fetch_object(mysql_query("SELECT * FROM settings"));
?>
change the collate and character set to utf8 for the table
alter table <some_table> convert to character set utf8 collate utf8_unicode_ci;
i got my register page but when the submit button is pressed it doesn't carry out the checks that it should. instead it misses them all out for some strange reason and returns the page with no error text.
<?php
require "PasswordHash.php";
require "header.php";
require "globe.php";
echo "<body>
<div class='container'>";
echo "<div class='centered'>
<ul id='nav'>
<li><a href='login.php'>Home </a></li>
<li><a href='register.php'>Register</a></li>
<li><a href='forgotpassword.php'>Forgot Password</a></li>
<li><a href='contact.php'>Contact</a></li>
<li><a href='t&c.php'>Terms and Conditions</a></li>
</ul>";
echo"
<img src='banner1.jpg' width='800px' height='200px' />
<div class='regban'>
<img src='outsideimage/registertop.png' width='800px' height='40px' />
</div>
<div class='registertext'>
Registiring to Zone Wars allows you to be that one step closer to being part of our fantastic community! Simply register for free and with our quick registration form you will be playing very soon! <br />
<font color='red'><i>Please note registration is not currently taking place due to large maintenance. We are sorry for any inconvenience this may have caused. </i></font>";
$regsec = htmlentities($_SERVER['PHP_SELF']);
if (isset($_POST['register']))
{
$user = trim($_POST['user']);
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$email = trim($_POST['email']);
$email2 = $_POST['email2'];
$gender = $_POST['gender'];
$error_string = '';
require_once('recaptchalib.php');
$privatekey = "HIDDEN AS ITS PRIVATE";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$hasher = new PasswordHash(8, false);
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
function isValidEmail($email = '')
{
return preg_match("/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix",$email);
}
$userrow = mysqli_query($mysqli, "SELECT * FROM Persons WHERE username = '" . mysqli_real_escape_string($mysqli, $user) . "'");
$row_cnt = mysqli_num_rows($userrow);
$emailrow = mysqli_query($mysqli, "SELECT * FROM Persons WHERE email = '" . mysqli_real_escape_string($mysqli, $email) . "'");
$row_cnt1 = mysqli_num_rows($emailrow);
if (!$resp->is_valid) {
$error_string .= '<center>The reCAPTCHA wasnt entered correctly. Go back and try it again.</center><br />';
}
else if ($user == '') {
$error_string .= '<center>You left the Username field blank!.</center><br />';
}
else if (strlen($user) < 4) {
$error_string .= '<center>Your Username must be at least 4 characters long.</center><br />';
}
else if (strlen($user) > 8) {
$error_string .= '<center>You Username cannot be longer then 8 characters.</center><br />';
}
else if ( !preg_match("/^[a-z]+[\w.-]*$/i", $user) ) {
$error_string .='<center>Your username may only contain letters, numbers, dots, underscores, hyphen and start with a letter</center>';
}
else if ($row_cnt != 0) {
$error_string .= '<center>Your Username exists</center><br />';
}
else if ($pass1 == '')
{
$error_string .='<center>You left the password field blank.<br /></center>';
}
else if ($pass2 == '') {
$error_string .='<center>You left the confirmation password blank<br /></center>';
}
else if ($pass1 != $pass2) {
$error_string .='<center>Your password and confirmation password do not match<br /></center>';
}
else if(strlen($pass1) > 72) {
$error_string .='<center>Your password cannot be longer then 72 characters<br /></center>';
}
else if ($email == '') {
$error_string .='<center>You left the email field blank!.<br /></center>';
}
else if ($email != $email2) {
$error_string .='<center>Your email and confirmation email did not match.<br /></center>';
}
else if (!isValidEmail($email)) {
$error_string .= '<center>Please enter a valid email address.<br></center>';
}
else if ($row_cnt1 != 0) {
$error_string .= '<center>Your email address exists</center><br />';
}
else {
if ($error_string != '') {
echo "<font color=red> '$error_string' </font><br /><center> Please go back and fix the errors <a href=register.php>here</a></center>";
}
else {
$hash = $hasher->HashPassword($pass1);
get_post_var($user);
get_post_var($email);
$euser = mysqli_real_escape_string($mysqli, $user);
$eemail = mysqli_real_escape_string($mysqli, $email);
if (strlen($hash) >= 20) {
mysqli_query($mysqli, "INSERT INTO Persons (Username, Password, Email, Gender) VALUES ('$euser', '$hash', '$eemail', '$gender')");
echo "You have signed up to the game! Please login <a href='login.php'here</a>. ";
}
else
{
echo "<center>A fatal error occured. Please contact the Admin board</center><br />";
}
}
}
}
else
{
echo "
<form action='$regsec' method='POST'>
<table align='center' border='0'>
<tr><td align='right'>Username:</td><td><input type='text' name='user' /></td></tr>
<tr><td align='right'>Password:</td><td><input type='password' name='pass1' /></td></tr>
<tr><td align='right'>Confirm Password:</td><td><input type='password' name='pass2' /></td></tr>
<tr><td align='right'>Email Address:</td><td><input type='text' name='email' /></td></tr>
<tr><td align='right'>Confirm Email Address:</td><td><input type='text' name='email2' /></td></tr>
<tr><td align='right'>Gender:</td><td><select name='gender'><option value='Male'>Male</option><option value='Female'>Female</option></select></td></tr>
<tr><td colspan='2'><center>";
require_once('recaptchalib.php');
$publickey = "HIDDEN AS ITS PRIVATE"; // you got this from the signup page
echo recaptcha_get_html($publickey);
echo "</center></td><td></td></tr>
<tr><td colspan='2'><center>By registring you have read and agreed our <a href='t&c.php'>Terms and Conditions</a></center></td><td></td></tr>
<tr><td colspan='2'><center><input type='submit' name='register' value='register'></center></td><td></td></tr>
</table></form>";
}
echo "</div>
<img src='outsideimage/registerbott.png' width='800px' height='20px' />
</div>";
echo " <br />
<div class='image'>
<img alt='' src='outsideimage/bottom.png' />
<div class='text'>
<small>Copyright © 2012 All Rights Reserved.</small>
</div>
<div class='text1'>
<small>";
date_default_timezone_set('Europe/London');
echo date('l jS \of F Y h:i:s A');
echo "</small>
</div>
</div>
</body>";
?>
You are not getting any error messages because you are not printing it out. You assign your error messages to variable $error_string, but there's no where in the code where it prints it out. Try putting an echo after your last else statement.
if (!$resp->is_valid) {
...
}
else if ($user == '') {
...
}
else if (strlen($user) < 4) {
...
}
...
else {
...
}
echo $error_string;
Also, seems like the last else in your validation seems unnecessary since you're checking if $error_string is empty or not.
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;
});
});
});