How to validate form in jQuery and PHP - php

I have a registration form that I want to validate using jQuery and than pass it to PHP to login if all details are correct.
I am trying to use Yendesigns form - http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/
My form code is:
<?php
require_once("includes/initialise.php");
if (isset($_POST['resetpassword']) && $_POST['resetpassword'] == 'resetnow') {
$required = array('first_name','last_name','username','email','password','password2');
$missing = array();
$validation = array(
'first_name' => 'Please provide your first name',
'last_name' => 'Please provide your last name',
'username' => 'Please provide your username',
'email' => 'Please provide your valid email address',
'password' => 'Please provide your password',
'password2' => 'Please confirm your password',
'userdup' => 'Username already registered',
'emaildup' => 'Email address already registered',
'mismatch' => 'Passwords do not match'
);
//Sanitise and clean function
$first_name = escape($_POST['first_name']);
$last_name = escape($_POST['last_name']);
$username = escape($_POST['username']);
$email = escape($_POST['email']);
$password = escape($_POST['password']);
$password2 = escape($_POST['password2']);
foreach($_POST as $key => $value) {
$value = trim($value);
if(empty($value) && in_array($key,$required)) {
array_push($missing,$key);
} else {
${$key} = escape($value);
}
}
if($_POST['email'] !="" && getDuplicate(1,'email','clients','email',$email)) {
array_push($missing,'emaildup');
}
if($_POST['username'] !="" && getDuplicate(1,'username','clients','username',$username)) {
array_push($missing,'userdup');
}
// Check User Passwords
if( strcmp($_POST['password'], $_POST['password2']) != 0 ) {
array_push($missing,'mismatch');
}
//validate email address
if(!empty($_POST['email']) && !isEmail($_POST['email'])) {
array_push($missing,'email');
}
if(!empty($missing)) {
$before = " <span class=\"errorred\">";
$after = "</span>";
foreach($missing as $item)
${"valid_".$item} = $before.$validation[$item].$after;
} else {
// stores MD5 of password
$passmd5 = md5($_POST['password']);
// stores clients IP addresss
$user_ip = $_SERVER['REMOTE_ADDR'];
// Automatically collects the hostname or domain like example.com)
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$date = date('Y-m-d');
$time = date('H:i:s');
// Generates activation code simple 4 digit number
$hash = mt_rand().date('YmdHis').mt_rand();
//Insert Data
$sql = "INSERT INTO clients(first_name, last_name, username, email, password, date, time, `hash`)
VALUES ('{$first_name}','{$last_name}','{$username}','{$email}','$passmd5','$date', '$time','$hash')";
$result = mysql_query($sql, $conndb) or die(mysql_error());
if($result) {
$to = $_POST['email'];
$subject = 'Activate your account';
$from = 'dummy#emailaddress.co.uk';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=UTF-8\r\n";
$headers .= "From: My Website Name <".$from.">\r\n";
$headers .= "Reply-to: My Website Name <".$from.">\r\n";
$message = '<div style="font-family:Arial, Verdana, Sans-serif; color:#333; font-size:12px">
<p>Thank you for registering on our website</p>
<p>Please click on the following link to activate your account:
http://'.$host.''.$path.'/activate.php?id='.$hash.'</p>
<p>Here are your login details...</p>
<p>User Name: '.$username.'</p>
<p>Email: '.$email.' </p>
<p>Passwd: '.$password.' </p>
</p></div>';
if (mail($to, $subject, $message, $headers)) {
$confirmation = '<p>Thank you.<br />You have successfully registered.</p>';
} else {
$confirmation = '<p>Error.<br />Your activation link could not be sent.<br />Please contact administrator.</p>';
}
}
}
}
require_once("includes/header.php");
?>
<div class="block">
<div class="block_head">
<div class="bheadl"></div>
<div class="bheadr"></div>
<h5>Register</h5>
<ul>
<li>Login</li>
</ul>
</div> <!-- .block_head ends -->
<div class="block_content">
<?php echo isset($confirmation) ? $confirmation : NULL; ?>
<form name="register" id="customForm" action="" method="post">
<div>
<label for="first_name">First Name: * <?php echo isset($valid_first_name) ? $valid_first_name : NULL; ?></label>
<input id="first_name" name="first_name" type="text" class="fld" value="" />
<span id="first_nameInfo"></span>
</div>
<div>
<label for="last_name">Last Name: * <?php echo isset($valid_last_name) ? $valid_last_name : NULL; ?></label>
<input id="last_name" name="last_name" type="text" class="fld" value="" />
<span id="last_nameInfo"></span>
</div>
<div>
<label for="username">Username: * <?php echo isset($valid_username) ? $valid_username : NULL; ?> <?php if(isset($valid_userdup)) { echo $valid_userdup; } ?></label>
<input id="username" name="username" type="text" class="fld" value="" />
<span id="usernameInfo"></span><span id="status"></span>
</div>
<div>
<label for="email">E-mail: * <?php if(isset($valid_email)) { echo $valid_email; } ?> <?php if(isset($valid_emaildup)) { echo $valid_emaildup; } ?></label>
<input id="email" name="email" type="text" class="fld" value="" />
<span id="emailInfo"></span>
</div>
<div>
<label for="pass1">Password: * <?php if(isset($valid_password)) { echo $valid_password; } ?></label>
<input id="pass1" name="pass1" type="password" class="fld" value="" />
<span id="pass1Info"></span>
</div>
<div>
<label for="pass2">Confirm Password: * <?php if(isset($valid_password2)) { echo $valid_password2; } ?> <?php if(isset($valid_mismatch)) { echo $valid_mismatch; } ?></label>
<input id="pass2" name="pass2" type="password" class="fld" value="" />
<span id="pass2Info"></span>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</table>
<input type="hidden" name="resetpassword" value="resetnow" />
</form>
</div>
<!-- .block_content ends -->
<div class="bendl"></div>
<div class="bendr"></div>
</div>
<?php
require_once("includes/footer.php");
?>
And the jquery is:
/***************************/
//#Author: Adrian "yEnS" Mato Gondelle & Ivan Guardado Castro
//#website: www.yensdesign.com
//#email: yensamg#gmail.com
//#license: Feel free to use it, but keep this credits please!
/***************************/
$(document).ready(function(){
//global vars
var form = $("#customForm");
var first_name = $("#first_name");
var first_nameInfo = $("#first_nameInfo");
var last_name = $("#last_name");
var last_nameInfo = $("#last_nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
//On blur
first_name.blur(validateName);
last_name.blur(validateLastName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
first_name.keyup(validateName);
last_name.keyup(validateLastName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() & validateLastName() & validateEmail() & validatePass1() & validatePass2() & validateMessage())
return true
else
return false;
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Please provide a valid email address");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(first_name.val().length < 4){
first_name.addClass("error");
first_nameInfo.text("Please provide your first name (more than 3 letters)");
first_nameInfo.addClass("error");
return false;
}
//if it's valid
else{
first_name.removeClass("error");
first_nameInfo.text("");
first_nameInfo.removeClass("error");
return true;
}
}
function validateLastName(){
//if it's NOT valid
if(last_name.val().length < 4){
last_name.addClass("error");
last_nameInfo.text("Please provide your first name (more than 3 letters)");
last_nameInfo.addClass("error");
return false;
}
//if it's valid
else{
last_name.removeClass("error");
last_nameInfo.text("");
last_nameInfo.removeClass("error");
return true;
}
}
function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Please provide your password (at least 5 characters)");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("");
pass2Info.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
});
When I click the submit button the form passes via php and stops the jquery. If the submit button is not pressed than it carries on validating via jQuery.
How can I get it to if all details are correct to pass the PHP validation too. If errors or user has jQuery disabled to validate via PHP?
Thank you

A good web application has two layers of validation:
The input is validated client side with javascript (e.g. jquery). It gives better feedback for the user if the validation is done immediately without contacting the server.
The input is validated server side to guard against malicious users having bypassed the client side validation (or simply a user with javascript disabled). There are also cases where validation rules are hard to implement client side.
If you want to test your server side validation, the easiest is probably to temporary disable javascript in the browser.

METHOD 1: In your jQuery (untested):
$("#send").click(function(e) {
e.preventDefault();
// call javascript validation functions here
// if valid then submit form:
$("#customForm").submit();
});
EDIT: If user has not got javascript, then the form will be submitted as usual and validated by php only when the submit button is clicked. But if javascript is enabled, then the default submit action will be prevented, and you can first check whatever you want to check on the client side before submitting the form.
METHOD 2: Instead of the jQuery code above, you can instead call your javascript validation functions with an onSubmit="return validate();" form attribute, where validate() javascript function returns false if there are errors. This will also prevent the form from submitting directly - unless the user does not have javascript.
UPDATE IN RESPONSE TO ZAFER's COMMENT:
In method 1, might be better to use this instead:
$("#customForm").submit(function(e) {
e.preventDefault();
// call javascript validation functions here
// if valid then submit form:
$(this).submit();
});

to insert into a database i use this function.
/**
* Takes an array or string and takes out malicous code.
* #param array|string $var
* #param string $key
* #return string
*/
function aspam($var, $returnZero = false, $key = '') {
if (is_array($var) && !empty($key)) {
/*
* if var is array and key is set, use aspam on the array[key]
* if not set, return 0 or ''
*/
if (isset($var[$key])) {
return general::aspam($var[$key], $returnZero);
} else {
return ($returnZero) ? 0 : '';
}
} elseif (is_array($var) && empty($key)) {
/*
* if var is array and key is empty iterate through all the members
* of the array and aspam the arrays and take out malicous code of the
* strings or integers.
*/
$newVar = array();
$newVal = '';
foreach ($var as $key => $val) {
if (is_array($val)) {
$newVal = general::aspam($val, $returnZero);
} elseif (!empty($val)) {
$newVal = trim(htmlspecialchars($val, ENT_QUOTES));
} else {
$newVal = ($returnZero) ? 0 : '';
}
$newVar[$key] = $newVal;
}
return $newVar;
} elseif (!empty($var)) {
/*
* Strip malicous code
*/
return trim(htmlspecialchars($var, ENT_QUOTES));
} else {
/*
* return default 0 | '' if string was empty
*/
return ($returnZero) ? 0 : '';
}
}
to use this function you put in the array, then tell it if you want to return empty or 0.
$product_id = aspam($_REQUEST, true, 'product_id');
The javascript with jquery you can itterate through a class and validate all at once.
/*variable to check if it is valid*/
var returnVar = true;
$('.required').each(function () {
if ($(this).is("select")) {
if ($(this).val() > '0') {
/*Code for is valid*/
$(this).parent().removeClass("alert-danger");
} else {
/*Code for is not valid*/
$(this).parent().addClass("alert-danger");
returnVar = false;
}
} else {
if (!$(this).val()) {
/*Code for is valid*/
$(this).parent().addClass("alert-danger");
returnVar = false;
} else {
/*Code for is not valid*/
$(this).parent().removeClass("alert-danger");
}
}
});
if(returnVar){
/*submit form*/
}

Related

My form Verification and Validation with php is not working

I have to verify and validate information inputted in an HTML form against a database created in phpMyAdmin. Currently, when I input my data and hit submit, I get a message that I have at the end of my PHP file. (Account not found). Also whatever transaction they select should be redirected to that page.
Is it giving me an error msg because I have the wrong name somewhere or is it skipping over all the functions?
This is the Form
<body>
<form name="form" action="Verify.php" method="post">
<h1>Lushest Lawns and Landscaping</h1>
<label for="input"><b>Landscaper's First Name: </b></label>
<input type="text" name="fname" placeholder="Example: John" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Last Name: </b></label>
<input type="text" name="lname" placeholder="Example: Doe" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Password: </b></label>
<input type="password" name="pass" placeholder="Example: Ba9877bb$Bb9" required >
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's ID#: </b></label>
<input type="number" name="id" placeholder="Example: 123456" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Phone#: </b></label>
<input type="number" name="Pid" placeholder="Example: 1234567890" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Email: </b></label>
<input type="text" name="email" placeholder="Example: abc#abc.com">
<br>
<label for="input"><br><b>Select a Transaction: </b></label>
<select id="transaction" name="transaction" required>
<option name="1">Search A Landscaper's Accounts</option>
<option name="2">Book A Customer's Appoinment</option>
<option name="3">Place A Customer's Order</option>
<option name="4">Update A Customer's Order</option>
<option name="5">Cancel A Customer's Appoinment</option>
<option name="6">Cancel A Customer's Order</option>
<option name="7">Create A New Customer Account</option>
</select>
<br>
<input type="checkbox" id="confirmation" name="emailconfirm">
<label for="checkbox"><b>Email the Transaction Confirmation</b></label>
<button class="button button5" name="submit">Submit</button>
</form>
</body>
This is the PHP file. I just removed the server name and everything for now but I have it in my file.
<?php
if(isset($_POST["submit"])){
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
$connection = mysqli_connect($server,$username,$password,$dbname);
if($connection-> connect_error){
die("Connection failed: " . $connection-> connect_error);
}
//Form input data
$Fname = $_POST["fname"];
$Lname = $_POST["lname"];
$Lid = $_POST["id"];
$Lpass = $_POST["pass"];
$transaction = $_POST["transaction"];
$Lemail = $_POST["email"];
$Lphone = $_POST["Pid"];
$_SESSION['id'] = $Lid;
$validate = true;
$verify = false;
function validate() {
//validate first name
if (empty($_POST["fname"])) {
echo ("First Name is required <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate last name
if (empty($_POST["lname"])) {
echo ("Last Name is required <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate id
if (empty($_POST["id"])) {
echo("Invalid ID: Enter 6-digit number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate password
if (empty($_POST["pass"])) {
echo("Invalid Password: Enter 6-digit number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//Validate transaction
if (empty($_POST["transaction"])) {
echo ("Please select a Transaction <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//Validate phone number
if (empty($_POST["Pid"])) {
echo("Invalid Phone Number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate email
if(isset($_POST["emailconfirmation"]) && !empty($_POST["emailconfirmation"])) {
if(empty($_POST["emailconfirmation"])) {
echo("Please enter an Email <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
} else {
$email = $_POST["emailconfirmation"];
if (!filter_var($email, 'FILTER_VALIDATE_EMAIL')) {
echo ("Invalid Email Format, Correct Format: email#example.com <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
}
}
}
function verify($connection) {
$sql = "SELECT * FROM `Landscaper DB`";
$result = $connection -> query($sql);
while ($row = $result-> fetch_assoc()) {
if (($_POST["fname"]) == ($row["LFirstName"])) {
if (($_POST["lname"]) == ($row["LLastName"])) {
if ($_POST["id"] == $row["LID"]) {
if ($_POST["Pid"] == $row["LPhone"]) {
if ($_POST["pass"] == $row["LPassword"]){
return true;
}
}
}
}
}
}
return false;
}
validate();
if(validate()) {
$verify = verify($connection);
}
if($verify) {
//transaction
if($transaction == "1") {
header("Location: Landscaper.php" );
}
elseif($transaction == "2") {
header("Location: AppoinmentForm.html" );
}
elseif($transaction == "3") {
header("Location: OrderForm.html");
}
elseif($transaction == "4"){
header("Location: UpDateOrder.html" );
}
elseif($transaction == "7"){
header("Location: CreateAccount.html" );
}
elseif($transaction == "5"){
header("Location: CancelCusApoin.html" );
}
elseif($transaction == "6"){
header("Location: CancelOrder.html" );
}
}
else {
echo "Sorry, account not found.\n Please try again with a valid Name, ID, and Password.";
header( "refresh:3;url=Pro4.html" );
}
$connection -> close();
}
?>
DATABASE
This is the table of inputs that should work.
You're not going to pass validation because your select element options have no values, so transaction will be blank.
You have lots of badly formed html. Read up on forms, labels, input elements, and IDs, names, and values. Once you have the html ironed out then the server side validation will follow.
validate();
if(validate()) {
$verify = verify($connection);
}
For whatever reason you are calling the validate() function twice. You only need to call it once. Additionally, you are checking the return value of the validate() function with an if() statement, but your validate() function does not have any return statement. This means that the "return value" of this function is always NULL. This will result in the following code/execution:
validate();
if(NULL) {
$verify = verify($connection);
}
That way the if() block is never executed. So your verify() function is never called and your $verify variable is never updated, it stays false. When you want to use your verify() function in an if() statement, your function has to use the return statement to return a "result" like return true; or return false;.
Your $_POST['transaction'] field does not contain the name="..." values but instead the label content of the <option> entry. The syntax to set a (different) value for an <option> entry is set the value="..." attribute, something like:
<option value="4">Update A Customer's Order</option>
You can always check with var_dump($_POST); to see what the actual values are the browser is sending to your PHP script.

keeping first field in html form after submitting then have a master submit button after someone is done with the first field

I am currently using this php form to submit into our mySQL database with a "chip_number" and "order_number" also with a date and time stamp. We want to use this with no keyboard or mouse, just a scanner. Currently it tabs the first field and when the second field is scanned the form is submitted, which is working as intended but it completely starts the form over, i would like it to keep the first field (order_number) after submitting so we can scan multiple "chip_numbers" on the same "order_number" then have a Master submit button if you will to send it all through when the employee is done with that order number and start with a blank form. This is the script i am using. thanks to all in advance!
<!-- Insert -->
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
IF (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: TRY AGAIN HUMAN!";
}
mysqli_close($conn);
?>
<html>
<head>
<!-- Validate form function -->
<!--<script type="text/javascript">
// function validateForm()
// {
// var x=document.forms["chip_insert"]["order_number"].value;
// var y=document.forms["chip_insert"]["chip_number"].value;
// if (x==null || x=="")
// {
// alert("Please enter an Order Number.");
// document.forms["chip_insert"]["order_number"].focus();
// return false;
// }
// if (y==null || y=="")
// {
// alert("Please enter a Microchip Number.");
// document.forms["chip_insert"]["chip_number"].focus();
// return false;
// }
// }
</script>
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body onLoad="document.chip_insert.order_number.focus();">
<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post">
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>
header('Location: http://JVSIntranet/microchip/homeagain.php');
This code redirects back to the form, I guess. You should add the ordernumber so it can be picked up by the form.
$ordernr = $_POST['order_number'];
header("Location: http://JVSIntranet/microchip/homeagain.php?order_number=$ordernr"); //mark the double quotes
in your form code you will have to use something like
<?php $value = (isset($_GET['order_number'])) ? " value=$_GET['order_number'] " : ""; ?>
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" <?php echo $value; ?> required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
I finally got it. i had to take out the Return function from my form and i added this to my script:
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
then i put this in my input line and it works fine:
value="<?php echo $value; ?>"

Values not inserting in database with php

I have created a user register form with php jquery and sql and i am
trying to enter the details in database via ajax request, code is
executing perfectly but values are not entering in the database, and i
have checked my query too by running it in the sql editor query also
working fine,
can you tell where is the error ?
<!DOCTYPE html>
<html>
<head>
<title>Login Register Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
/**
* Created by pratyush on 8/28/14.
*/
$(function(){
$("input[name='btn_submit_reg']").click(function(){
registerUser();
});
$("input[name='btn_submit_login']").click(function(){
loginUser();
});
});
function registerUser(){
if(IsValidFormReg()){
var frm = $(".register").serialize();
$.ajax({
url : 'modal/registerdao.php',
type : 'POST',
data : frm,
success : function(result) {
if (result.indexOf("correct") > -1) {
alert(frm);
window.location.replace("registrationconfirm.php");
}
}
});
}
}
function IsValidFormReg()
{
var valid= true;
var username = $("input[name='username_reg']").val();
var userpass = $("input[name='userpass_reg']").val();
var email = $("input[name='useremail_reg']").val();
if(username.length==0){
valid = false;
$("input[name='username_reg']").addClass("formerror");
}
if(userpass.length==0){
valid = false;
$("input[name='userpass_reg']").addClass("formerror");
}
if(email.length==0){
valid = false;
$("input[name='useremail_reg']").addClass("formerror");
}
else{
if(checkemail(email)==false){
valid = false;
$("input[name='useremail_reg']").addClass("formerror");
alert("please enter valid email");
}
}
if(!valid)
$(".formentrieserror").html(" Please fill correct form entries...");
else
$(".formentrieserror").html(" ");
return valid;
}
function checkemail(email){
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.length>0){
if (!filter.test(email))
return false;
else
return true;
}
else
return false;
}
function loginUser(){}
<style>
.formerror{border: solid 2px red;}
</style>
</head>
<body>
<h2>Login Form</h2> <br><br>
<form class="login">
<input type="text" name="username_login" placeholder="user name"> <br> <br>
<input type="password" name="userpass_login" placeholder="password"><br> <br>
<input type="button" name="btn_submit_login" value="Login">
</form>
<br><br>
<h2>Registration Form</h2>
<br><br>
<form class="register">
<input type="text" name="username_reg" placeholder="user name"> <br> <br>
<input type="password" name="userpass_reg" placeholder="password"><br> <br>
<input type="email" name="useremail_reg" placeholder="email"><br> <br>
<input type="button" name="btn_submit_reg" value="Register">
</form>
<div class="formentrieserror"></div>
</body>
</html>
//registerDao.php..................................//
<?php
class RegisterUserInfo{
public $userName;
public $userPassword;
public $userEmail;
}
class userRegisterDao {
function RegisterUser($registration_info) {
include_once ("database.php");
$qry = "insert into userdetails(
userName,
userPassword,
userEmail)
values('".$registration_info->userName."','"
.$registration_info->userPassword."','"
.$registration_info->userEmail."')";
return Database::executeQuery($qry); // return true or false
}
}
$userName = mysql_escape_string($_REQUEST ['userName']);
$userPassword = mysql_escape_string($_REQUEST ['userPassword'] );
$userEmail = mysql_escape_string($_REQUEST ['userEmail'] );
$registration_info = new RegisterUserInfo();
$registration_info->userName=$userName;
$registration_info->userPassword=$userPassword;
$registration_info->userEmail=$userEmail;
$dao = new userRegisterDao();
$insert = $dao->RegisterUser($registration_info);
if($insert===true){
echo "correct";
}
else
echo "invalid";
?>
Change this line
$userName = mysql_escape_string($_REQUEST ['userName']);
$userPassword = mysql_escape_string($_REQUEST ['userPassword'] );
$userEmail = mysql_escape_string($_REQUEST ['userEmail'] );
to this
$userName = mysql_escape_string($_REQUEST ['username_reg']);
/* changed ^^ */
$userPassword = mysql_escape_string($_REQUEST ['userpass_reg'] );
/* changed ^^ */
$userEmail = mysql_escape_string($_REQUEST ['useremail_reg'] );
/* changed ^^ */
I see this alot... Ajax with no error handler, just success handlers. Why not have php return errors to ajax and output to console IE console.log( some_error ) . It will make debugging a lot easier in the future.
I also see that there is no sql exception handling. That would have shown you that no column exists by that name during attempted insertions.
just a few debugging tips going forward, good luck.

Registration page not processing data to database

I am developing a website with User registration and login ,after completing the page configuration ,i tried to register it worked perfectly and later next day i tried to register but the page is not loading ,after filling in the data and if i click submit ,it reloads the same register page with no effect ,how to solve this problem
SQL Query Processing code: (class.newuser.php)
enter code here
class User
{
public $user_active = 0;
private $clean_email;
public $status = false;
private $clean_password;
private $clean_username;
private $unclean_username;
public $sql_failure = false;
public $mail_failure = false;
public $email_taken = false;
public $username_taken = false;
public $activation_token = 0;
function __construct($user,$pass,$email)
{
//Used for display only
$this->unclean_username = $user;
//Sanitize
$this->clean_email = sanitize($email);
$this->clean_password = trim($pass);
$this->clean_username = sanitize($user);
if(usernameExists($this->clean_username))
{
$this->username_taken = true;
}
else if(emailExists($this->clean_email))
{
$this->email_taken = true;
}
else
{
//No problems have been found.
$this->status = true;
}
}
public function userPieAddUser()
{
global $db,$emailActivation,$websiteUrl,$db_table_prefix;
//Prevent this function being called if there were construction errors
if($this->status)
{
//Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
//Construct a unique activation token
$this->activation_token = generateactivationtoken();
//Do we need to send out an activation email?
if($emailActivation)
{
//User must activate their account first
$this->user_active = 0;
$mail = new userPieMail();
//Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE",array("{$websiteUrl}/",$this->activation_token));
//Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array("#ACTIVATION-MESSAGE","#ACTIVATION-KEY","#USERNAME#"),
"subjectStrs" => array($activation_message,$this->activation_token,$this->unclean_username)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if(!$mail->newTemplateMsg("new-registration.txt",$hooks))
{
$this->mail_failure = true;
}
else
{
//Send the mail. Specify users email here and subject.
//SendMail can have a third parementer for message if you do not wish to build a template.
if(!$mail->sendMail($this->clean_email,"New User"))
{
$this->mail_failure = true;
}
}
}
else
{
//Instant account activation
$this->user_active = 1;
}
if(!$this->mail_failure)
{
//Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `".$db_table_prefix."users` (
`username`,
`username_clean`,
`password`,
`email`,
`activationtoken`,
`last_activation_request`,
`LostpasswordRequest`,
`active`,
`group_id`,
`sign_up_date`,
`last_sign_in`
)
VALUES (
'".$db->sql_escape($this->unclean_username)."',
'".$db->sql_escape($this->clean_username)."',
'".$secure_pass."',
'".$db->sql_escape($this->clean_email)."',
'".$this->activation_token."',
'".time()."',
'0',
'".$this->user_active."',
'1',
'".time()."',
'0'
)";
return $db->sql_query($sql);
}
}
}
}
?>
HTML register.php
enter code here
<?php
require_once("models/config.php");
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: index.php"); die(); }
?>
<?php
//Forms posted
if(!empty($_POST))
{
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
//Perform some validation
//Feel free to edit / change as required
if(minMaxRange(5,25,$username))
{
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT",array(5,25));
}
if(minMaxRange(8,50,$password) && minMaxRange(8,50,$confirm_pass))
{
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT",array(8,50));
}
else if($password != $confirm_pass)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if(!isValidemail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
//End data validation
if(count($errors) == 0)
{
//Construct a user object
$user = new User($username,$password,$email);
//Checking this flag tells us whether there were any errors such as possible data duplication occured
if(!$user->status)
{
if($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE",array($username));
if($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE",array($email));
}
else
{
if(!$user->userPieAddUser())
{
if($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if(count($errors) == 0)
{
if($emailActivation)
{
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
} else {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration | <?php echo $websiteName; ?> </title>
<?php require_once("head_inc.php"); ?>
</head>
<body>
<div class="modal-ish">
<div class="modal-header">
<h2>Sign Up</h2>
</div>
<div class="modal-body">
<div id="success">
<p><?php echo $message ?></p>
</div>
<div id="regbox">
<form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Password:</label>
<input type="password" name="password" />
</p>
<p>
<label>Re-type Password:</label>
<input type="password" name="passwordc" />
</p>
<p>
<label>Email:</label>
<input type="text" name="email" />
</p>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Register" />
</div>
</form>
</div>
<div class="clear"></div>
<p style="margin-top:30px; text-align:center;">Login / Forgot Password? / Home Page</p>
</body>
</html>
Its all due to div tags:
2 divisions closed within the form tag but they are opened outside the form tag.
So try by enclosing the whole form within one div(regbox) Including submit.
And make sure that no div is closed within form tag which is opened outside form tag.

Checking if a PHP array is empty in JavaScript

Hi I have a form where a user can enter one or more books into a DB. Whenever a user enters one book and forgets to enter the title, a JavaScript alert comes and alerts him to enter a title. Now if he has two or more books and he forgets to enter the title, the alert doesn't show up.
This is my JavaScript function.
function validateForm()
{
var a=document.forms["submit_books"]["title"].value;
if (a==null || a=="")
{
alert("Please enter a Title");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.submit_books.email.value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
}
And Here is my PHP code
<form method="post" name="submit_books" onsubmit="return validateForm()" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php for ($i=1; $i<$num_of_books + 1; $i++){
echo "<strong>Book # $i</strong><br><br>";
?>
<label for="title">*Title</label>: <input type="text" id="title" size="60" name="title[]" autocomplete="off"/><br><br>
<?php }?>
<input type="submit" name="submit" value="Submit Books">
</form>
I even tried putting the PHP array into a JavaScript one.
<?
$js_array = json_encode($title);
echo "var title = ". $js_array . ";\n";
?>
var index = 1;
if( index < title.length)
{
alert("Please enter a Title");
return false;
}
There must be an easier way doing this
You should be doing
var index = 1;
if( index > title.length )
{
alert("Please enter a Title");
return false;
}
Since there is no record if title.length = 0, that is, if 1 > 0 then there is no title.
You can also check
if( title.length === 0 )
Try to use inside html form
<label>
<span>Book Title: (required)</span>
<input name="book" type="text" placeholder="Please enter your books title" required autofocus>
</label>
Then use javascript to validate
(function() {
// Create input element for testing
var inputs = document.createElement('input');
// Create the supports object
var supports = {};
supports.autofocus = 'autofocus' in inputs;
supports.required = 'required' in inputs;
supports.placeholder = 'placeholder' in inputs;
// Fallback for autofocus attribute
if(!supports.autofocus) {
}
// Fallback for required attribute
if(!supports.required) {
}
// Fallback for placeholder attribute
if(!supports.placeholder) {
}
// Change text inside send button on submit
var send = document.getElementById('submit');
if(send) {
send.onclick = function () {
this.innerHTML = '...Processing';
}
}
})();
You can do this like:
<?
echo "var title_length = ". count($title) . ";\n";
?>
var index = 1;
if( index > title_length)
{
alert("Please enter a Title");
return false;
}

Categories