Having Problem with my PHP Code and Jquery - javascript

I need some help
Whenever I input all the information and wanted to click submit, it always alert me "You already submit before" but it was the first time i entered the information. So there shouldn't be any duplicate values.
And the data itself also didn't post into my phpmyadmin database.
Secondly, i added the addclass("error") and removeclass ('error') in the javascript. However only those selection questions will show the red error border line while text input questions didn't show the error border line even though it is wrong
I have spent days to investigate it but still couldn't solve it.
My index.php file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Refund Request Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" >
<!-- <script src="form.js"></script>-->
</head>
<body>
<div class="container">
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="form-container">
<span style="text-align: center;padding-bottom: 0px;"><br>
<center>
<h1>
Refund Request Form
</h1>
</center>
</span>
<form method="post" id="form" name="form">
<label for="school_num">School Number: <span class="required">*</span></label>
<input id="school_num" type="text" placeholder="Enter your School Number" name="school_num" maxlength="50">
<label for="name">Full Name: <span class="required">*</span></label>
<input id="name" type="text" placeholder="Enter your Name in Capital as per IC" name="name" maxlength="50">
<label for="email">Email Address: <span class="required">*</span></label>
<input id="email" type="text" placeholder="Enter your Email Address" name="email" maxlength="50">
<label for="ic_num">IC Number: <span class="required">*</span></label>
<input id="ic_num" type="number" placeholder="Enter your IC Number (without dash)" name="ic_num" data-parsley-length="[12,12]" maxlength="12">
<label for="nts">Event1 Refund Amount: <span class="required">*</span></label>
<select id="nts" placeholder="-" name="nts" onchange="sum()" >
<option value = "-" selected>-</option>
<option value = "0" >0</option>
<option value = "80">80</option>
<option value = "100">100</option>
<option value = "110">110</option>
<option value = "110">120</option>
</select>
<label for="pesta">Event2 Refund Amount: <span class="required">*</span></label>
<select id="pesta" placeholder="" name="pesta" onchange="sum()" >
<option value = "-" selected>-</option>
<option value = "0" >0</option>
<option value = "100">100</option>
<option value = "360">360</option>
<option value = "450">450</option>
<option value = "460">460</option>
<option value = "535">535</option>
<option value = "540">540</option>
</select>
<label for="remarks">Remarks:</label>
<textarea id="remarks" name="remarks" placeholder="Type your remarks here" rows="5" maxlength="6000"></textarea>
<label style="border-bottom:1px dotted grey; padding-top: 30px;" colspan="2"></label>
<label for="refund" class="refund" style="color:#faa51a;font-family: 'Open Sans', sans-serif;font-weight: 500; font-size: 150%;width: 30%">Refund Total: </label>
<input id="refund" class="refund1" value="0" readonly style="border:none;color:#faa51a;font-family: 'Open Sans', sans-serif;font-weight: 500;font-size: 150%;width: 20%">
<!-- <input type="hidden" id="refund" name="refund" class="refund1" value="0" > -->
<input class="button-primary" name="submit" id="submit" role="button" type="button" onClick="validateForm()" value="Submit">
<!-- <input type="button" class="button-primary" type="submit" name="submit" id="submit" role="button" value="Submit">-->
</form>
<div id="success_message" style="display:none">
<h3>Submitted the form successfully!</h3>
<p> We will get back to you soon. </p>
</div>
<div id="error_message" style="width:100%; height:100%; display:none; "> <h3>Error</h3> Sorry there was an error sending your form.</div>
</div>
</div>
</body>
<script>
$(document).ready(function() {
//this calculates values automatically
sum();
$("#nts, #pesta").on("keydown keyup", function() {
sum();
});
});
function sum() {
var nts = document.getElementById('nts').value;
var pesta = document.getElementById('pesta').value;
var refundTotal = parseInt(nts) + parseInt(pesta);
if (!isNaN(refundTotal)) {
document.getElementById('refund').value ="RM " + refundTotal;
}
}
function validateEmail($email) {
var re = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ($email == '' || !re.test($email))
{
return false;
}
}
function validateAlphabet($account_name){
var letters = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if($account_name.value.match(letters))
{
return true;
}
else
{
return false;
}
}
// function validateNumber (){
//
// }
function validateForm() {
$('#submit').disable=true;
var valid = true;
var error_msg="";
//school number
if($('#school_num').val()=='' && $.trim($('#school_num').val()).length<=0 ){
error_msg+=("Please insert your school number\n");
$('#school_num').addClass("error");
valid=false;
}else{
$('#school_num').removeClass("error");
}
//name
if($('#name').val()==''){
error_msg+=("Please insert your name\n");
$('#name').addClass("error");
valid=false;
}else{
$('#name').removeClass("error");
}
//email
if($('#email').val()==''){
error_msg+=("Please insert your email address\n");
$('#email').addClass("error");
valid=false;
}else{
if(validateEmail(document.getElementById('email').value)==false){
//console.log(document.getElementById('email').value);
error_msg+=("Invalid email address, Please fill in the correct email\n");
$('#email').addClass("error");
valid=false;
}else{
$('#email').removeClass("error");
}
}
//ic number
if($('#ic_num').val()==''){
error_msg+=("Please insert your IC Number (without dash)\n");
$('#ic_num').addClass("error");
valid=false;
}else{
if(!$.isNumeric($("#ic_num").val())){
//console.log(document.getElementById('email').value);
error_msg+=("Invalid IC Number - should be numbers only (no dash)\n");
$('#ic_number').addClass("error");
valid=false;
}else{
$('#ic_number').removeClass("error");
}
}
//school
if($('#school').val()=='-'){
error_msg+=("Please select your school\n");
$('#school').addClass("error");
valid=false;
}else{
$('#school').removeClass("error");
}
//nts
if($('#nts').val()=='-'){
error_msg+=("Please select your NTS refund amount\n");
$('#nts').addClass("error");
valid=false;
}else{
$('#nts').removeClass("error");
}
//pesta
if($('#pesta').val()=='-'){
error_msg+=("Please select your PESTA refund amount\n");
$('#pesta').addClass("error");
valid=false;
}else{
$('#pesta').removeClass("error");
}
if(error_msg!=""){
alert(error_msg);
}
if(valid){
$.ajax({
url: 'form_ajax.php',
type: 'POST',
data: {
'action':'check_duplicate',
'school_num':$('#school_num').val(),
'name':$('#name').val(),
'email':$('#email').val(),
'school':$('#school').val(),
'nts':$('#nts').val(),
'pesta':$('#pesta').val(),
'refund':$('#refund').val(),
},
error: function() {
},
before:function(){
},
dataType: 'json',
success: function(data) {
if(data.is_duplicated==0){
$.ajax({
url: 'form_ajax.php',
type: 'POST',
data: {
'action':'submit_form',
'school_num':$('#school_num').val(),
},
before:function(){
},
dataType: 'json',
success: function(data) {
$('#submit').disable=false;
if(data.status==1){
alert(data.message);
$('#success_message').show()
//TOOD: Clear all input
$('#school_num').val(''),
$('#name').val(''),
$('#email').val(''),
$('#school').val(''),
$('#nts').val(''),
$('#pesta').val(''),
$('#refund').val('')
}else{
alert(data.message);
$('#error_message').show()
}
},
error: function() {
},
});
//TOOD: Clear all input
$('#school_num').val(''),
$('#name').val(''),
$('#email').val(''),
$('#school').val(''),
$('#nts').val(''),
$('#pesta').val(''),
$('#refund').val('')
}
else{
alert('You already submit before');
}
},
});
}else{
$('#submit').disable=false;
}
}
</script>
</html>
My form_ajax.php file
<?php
//if(isset($_POST['submit'])){
if($_POST['action']=='submit_form'){
require "config.php";
require "common.php";
$statement=false;
$new_student = array(
"school_num" => $_POST['school_num'],
"name" => $_POST['name'],
"email" => $_POST['email'],
"ic_num" => $_POST['ic_num'],
"school" => $_POST['school'],
"nts" => $_POST['nts'],
"pesta" => $_POST['pesta'],
"remarks" => $_POST['remarks'],
"refund" => $_POST['refund']
);
try{
//#1 Open Connection
$connection = new PDO ($dsn,$username,$password,$options);
//#2 Prepare Sql QUERY
$statement = $connection->prepare("INSERT INTO details (school_num,name, email, ic_num,school,nts,pesta,remarks,refund,date) values (?,?,?,?,?,?,?,?,?,NOW())");
$statement ->bindParam(1,$_POST['school_num'],PDO::PARAM_STR);
$statement ->bindParam(2,$_POST['name'],PDO::PARAM_STR);
$statement ->bindParam(3,$_POST['email'],PDO::PARAM_STR);
$statement ->bindParam(4,str_replace($_POST['ic_num'], '-', ''),PDO::PARAM_INT);
$statement ->bindParam(5,$_POST['school'],PDO::PARAM_STR);;
$statement ->bindParam(6,$_POST['nts'],PDO::PARAM_INT);
$statement ->bindParam(7,$_POST['pesta'],PDO::PARAM_INT);
$statement ->bindParam(8,$_POST['remarks'],PDO::PARAM_STR);
$statement ->bindParam(9,$_POST['refund'],PDO::PARAM_INT);
//$statement = $connection->prepare($sql);
$statement->execute();
$return_message=array('status'=>1,'message'=>'Your information has been saved');
echo json_encode($return_message);
} catch (PDOException $error){
$return_message=array('status'=>0,'message'=>'Sorry we cannot save your information');
echo json_encode($return_message);
}
}
if( $_POST['action']=='check_duplicate'){
require "config.php";
require "common.php";
$statement=false;
try{
//#1 Open Connection
$connection = new PDO ($dsn,$username,$password,$options);
//#2 Prepare Sql QUERY
$statement = $connection->prepare("SELECT details.school_num FROM details");
$statement->bindParam(':school_num', $_POST ['school_num'], PDO::PARAM_STR);
//$statement = $connection->prepare($sql);
$statement->execute();
$statement->fetchAll();
$return_message=array('status'=>1,'message'=>'there is duplicate');
echo json_encode($return_message);
}catch (PDOException $error){
$return_message=array('status'=>0,'message'=>'no duplicate');
echo json_encode($return_message);
}
}

In your code php does not return the is_duplicated variable. Therefore, data.is_duplicated is always undefined in javascript. That's why result of if check if(data.is_duplicated==0) will always false, because undefined not equal to 0.
try to replace this code
$return_message=array('status'=>1,'message'=>'there is duplicate');
to this
$return_message=array('status'=>1,'message'=>'there is duplicate', 'is_duplicated' => 1);
and here
$return_message=array('status'=>0,'message'=>'no duplicate');
to this
$return_message=array('status'=>0,'message'=>'no duplicate', 'is_duplicated' => 0);
P.S.
By the way, why you don't check what statement has? I guess is not correct.
//$statement = $connection->prepare($sql);
$statement->execute();
$statement->fetchAll();
$return_message=array('status'=>1,'message'=>'there is duplicate');
echo json_encode($return_message);
should be
//$statement = $connection->prepare($sql);
$statement->execute();
$results = $statement->fetchAll();
if (empty($results)) {
$duplicate = 0;
} else {
$duplicate = 1;
}
$return_message=array('status'=>1,'message'=>'there is duplicate', 'is_duplicated' = $duplicate);
echo json_encode($return_message);
P.P.S.
To check if there is data in the database is better to use count() and limit=1
GOOD LUCK

Related

How to set cookies for remember me checkbox after login in codeigniter?

view:
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
elogin = $("#elogin").val();
plogin = $("#plogin").val();
remember_me = $("#remember_me").val();
$.ajax({
type:"POST",
data:{"elogin":elogin,"plogin":plogin,"remember_me":remember_me},
url:"<?php echo base_url(); ?>login_redirect",
success: function(data) {
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect)
{
window.location.replace(data.redirect);
}
else
{
$(".login_success").html('<p>' + data.error + '</p>');
}
}
});
});
});
</script>
<div class="login_success"></div>
<label class="control-label">Your Email</label>
<input class="form-control" placeholder="" type="email" id="elogin">
<label class="control-label">Your Password</label>
<input class="form-control" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox"> Remember Me
<button class="btn btn-lg btn-primary full-width" id="login">Login</button>
Controller:
public function login_redirect()
{
$email = $this->input->post('elogin');
$password = $this->input->post('plogin');
$remember = $this->input->post('remember_me');
$this->db->select('*');
$this->db->from('user');
$where = "email='".$email."' and password='".$password."' and status='1'";
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result_array();
$this->session->set_userdata('user_id',$result);
if (!isset($_POST))
{
header ("Location:".base_url()."thankyou");
}
else
{
echo json_encode(array('redirect' => base_url().'thankyou'));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
}
In this code, I simply create a login form and do login via jquery ajax which is successfully working. Now, I want to set cookie after successful login via jquery ajax and cookie available only for one day after the day cookie expires. So, How can I do this? Please help me.
Thank You
View Page - Login.php :
<input type="email" class="form-control" name="email" placeholder="Enter Email" value="<?php if(isset($_COOKIE["email"])) { echo $_COOKIE["email"]; } ?>" required>
<input type="checkbox" name="remember" <?php if(isset($_COOKIE["email"])) { ?> checked <?php } ?> > Remember Me
Controller - LoginController.php
$email = $this->input->post('email');
$password = md5($this->input->post('password'));
$remember = $this->input->post('remember');
if(!empty($remember)) {
setcookie ("email",$email,time()+ 3600);
setcookie ("password",$password,time()+ 3600);
}else{
if(isset($_COOKIE["email"] && isset($_COOKIE["password"])) ){
setcookie ("email",""); setcookie ("password","");
}
}

PHP - run 1 insert query run twice record at the same time

addcustomer.php
<?php
include_once('functions.php');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8s" />
<title>Add Customer</title>
<script type="text/javascript">
function CheckFields()
{
var cusname = document.getElementById("cusname").value;
var cusadd = document.getElementById("cusadd").value;
if(cusname == '')
{
alert("Please enter your customer name");
return false;
}
if(cusadd == '')
{
alert("Please enter your customer address");
return false;
}
return true;
}
</script>
</head>
<body onLoad="focus();add.name.focus()">
<?php
if(array_key_exists('submit_check', $_POST))
{
if($_POST['submit'] == 'Add')
{
if(!AddCustomer(trim($_POST['cusname']), trim($_POST['cusgender']), trim($_POST['cusadd'])))
{
echo "Add Customer Error, Please try it again later";
}
else
{
echo "Customer Information had been successfully added into the database";
}
}
}
else
{
AddCustomerForm();
}
?>
</body>
</html>
dbconnect.php
<?php
$host = "localhost";
$user = "root";
$passwd = "";
$dbname = "customertest";
?>
functions.php
<?php
include('dbconnect.php');
function AddCustomerForm()
{
?>
<form id="add" name="add" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<b><u>Customer Details</u></b><br />
<input type="hidden" name="submit_check" value="1" />
Customer Name : <input type="text" id="cusname" name="cusname" maxlength="50" /><br />
Gender : <input type="radio" name="cusgender" value="M" checked />Male
<input type="radio" name="cusgender" value="F" />Female<br /><br />
<b><u>Customer Address</u></b><br />
Address : <input type="text" id="cusadd" name="cusadd" maxlength="100" size="50" /><br /><br />
<input type="submit" name="submit" value="Add" onclick="return CheckFields();" />
<input type="reset" name="reset" value="Reset" />
</form>
<?php
}
function ConnectToDb()
{
global $host, $user, $passwd, $dbname;
#$db = mysql_pconnect($host, $user, $passwd);
if(!$db)
{
echo "Couldn't connect to the database";
exit;
}
mysql_select_db($dbname);
}
function AddCustomer($cusname, $cusgender, $cusadd)
{
ConnectToDb();
$query = "INSERT INTO customer (cusname, cusgender, cusjoindate) VALUES (\"".$cusname."\", '".$cusgender."', NOW())";
$result = mysql_query($query);
if($result)
{
$cusID = mysql_insert_id();
$query = "INSERT INTO customer_address (cusID, cusaddress) VALUES ('".$cusID."', '".$cusadd."')";
$result = mysql_query($query);
return 1;
}
else
{
return 0;
}
}
?>
From above code, when I fill in the customer form and click Add button, I get the double record in my database as shown as image below:
I really don't understand why the database store 2 records at the same time.
Am I writing wrong code? Can someone help me?
Did u assigned the Primary & FOREIGN KEY Properly. Means the cusID in the customer address table that refers the cusID(Primary key) in customer table.I'm tried the same as bellow it works fine.
ALTER TABLE customer_address ADD FOREIGN KEY (cusID) REFERENCES customertest.customer(cusID) ON DELETE RESTRICT ON UPDATE RESTRICT;

Need to validate with javascript, php, update the DB table and redirect to login

Trying to get my customer registration page for a hotel database to validate the input with javascript then php, and update the database with the new customers info and redirect them to the correct login page (customerlogin).
When i click submit, state, telephone, country, suburb, title go blank and the other feilds remain with the info entered.
Please help thanks
<?php
require_once("dbconn.php");
$username = $pwrd = $repwrd = $gname = $sname = $addr = $suburb = $state = $ptcode = $mobile = $email = "";
$usernameErr = $pwrdErr = $repwrdErr = $gnameErr = $snameErr = $addrErr = $suburbErr = $stateErr = $ptcodeErr = $mobileErr = $emailErr = "";
//when the form is being submitted
if (isset($_POST["submit"]))
{
$username = mysqli_real_escape_string($dbConn, $_POST["uname"]);
if (empty($username))
$usernameErr = '<span class="error">Please enter a Unique ID</span>';
else {
$Npattern = "/^[a-zA-Z0-9]{1,20}+$/";
if (!preg_match($Npattern, $username))
{
$usernameErr = '<span class="error">Username already exists!</span>';
}
}
$pwrd = mysqli_real_escape_string($dbConn, $_POST["pword"]);
if (empty($pwrd))
$pwrdErr = '<span class="error">Please enter a password</span>';
else {
$PWpattern = "/^[a-zA-Z0-9]{6,20}+$/";
if ( !preg_match($PWpattern, $pwrd))
{
$pwrdErr = '<span class="error">Password must be minimum of 6 characters</span>';
}
}
$repwrd = mysqli_real_escape_string($dbConn, $_POST["pword2"]);
if ( empty($repwrd))
$repwrdErr = '<span class="error">Please ensure passwords match</span>';
else {
$pwrd = mysqli_real_escape_string($dbConn, $_POST["pword"]);
if (! $repwrd == $pwrd )
{
$repwrdErr = '<span class="error">Passwords do not match</span>';
}
}
$gname = mysqli_real_escape_string($dbConn, $_POST["FName"]);
if (empty($gname))
$gnameErr = '<span class="error">Please enter your First Name</span>';
else {
$Gpattern = "/^[a-zA-Z .\-]{1,20}+$/";
if ( !preg_match($Gpattern, $gname))
{
$gnameErr = '<span class="error">First Name can only contain alphabetical letters, spaces, hyphens and apostrophe';
$gnameErr .= 'it also must not exceed 20 characters</span>';
}
}
$sname = mysqli_real_escape_string($dbConn, $_POST["LName"]);
if (empty($sname))
$snameErr = '<span class="error">Please enter Last Name</span>';
else {
$Fpattern = "/^[a-zA-Z .\-]{1,20}+$/";
if ( !preg_match($Fpattern, $sname))
{
$snameErr = '<span class="error">Family Name can only contain alphabetical letters, spaces, hyphens and apostrophe';
$snameErr .= 'it also must not exceed 20 characters</span>';
}
}
$addr = mysqli_real_escape_string($dbConn, $_POST["add"]);
if (empty($addr))
$addrErr = '<span class="error">Please enter Address</span>';
else {
if (strlen($addr) > 40 )
{
$addrErr = '<span class="error">Your Address must not exceed 40 characters long </span>';
}
}
$state = mysqli_real_escape_string($dbConn, $_POST["state"]);
if ($state == "--" )
$stateErr = '<span class="error"> Please enter state</span>';
$ptcode = mysqli_real_escape_string($dbConn, $_POST["pcode"]);
if (empty($ptcode))
$ptcodeErr = '<span class="error">Please enter postcode</span>';
else {
$pcPattern = "/^[0-9]{4}$/";
if (!preg_match($pcPattern,$ptcode))
$ptcodeErr = '<span class="error">Postcode must be 4 digits</span>';
}
$mobile = mysqli_real_escape_string($dbConn, $_POST["mobile"]);
if (empty($mobile))
$mobileErr = '<span class="error">Please enter mobile number</span>';
else {
$Mobilepattern = "/^04?\d{8}$/";
if (!preg_match($Mobilepattern, $mobile))
$mobileErr = '<span class="error">Mobile number must be 10 digits</span>';
}
$email = mysqli_real_escape_string($dbConn, $_POST["email"]);
if (empty($email))
$emailErr = '<span class="error">Please Enter email address</span>';
else {
if ( filter_var($email,FILTER_VALIDATE_EMAIL))
{
$emailErr = '<span class="error">Email not Valid</span>';
}
}
}
else if (isset($_POST["reset"]))
{
unset($_POST["username"]);
unset($_POST["password"]);
unset($_POST["repassword"]);
unset($_POST["gname"]);
unset($_POST["sname"]);
unset($_POST["address"]);
unset($_POST["state"]);
unset($_POST["postcode"]);
unset($_POST["mobile"]);
unset($_POST["email"]);
unset($_POST[""]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration Form</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" language="javascript" >
function validateUsername(uname)
{
var uname = document.getElementById("uname").value;
if (uname.length < 21) {
return true;
} else {
Alert("Please choose a username with a max of 20 characters");
return false;
}
}
function validatePword(input)
{
var pword = document.getElementById("pword").value;
if (pword.length > 6) {
return true;
}
else
{
alert("Please choose a Password between 6 and 20 characters");
return false;
}
if (pword.length < 20) {
return true;
} else {
alert("Please choose a Password between 6 and 20 characters");
}
}
function confirmPword(input)
{
var pword = document.getElementById("pword").value;
var pword2 = document.getElementById("pword2").value;
if (pword2 == pword){
return true;
}
else
{
alert("Passwords do not match, please retype password in both feilds.");
}
}
function validateName(txt) {
var letters = /^[A-Za-z-']+$/;
if (txt.value.match(letters)) {
return true;
} else {
alert("Invalid Characters Entered for Name")
return false;
}
}
function validateAdd(input) {
var add = document.getElementById("add").value;
if (add.length < 41) {
return true;
} else {
alert("Address must not be more then 40 characters");
}
}
function validatePcode(input) {
var pcode = document.getElementById("pcode").value;
var numbers = "123456789";
if (pcode.length < 4) {
alert("Postcode must be 4 digits")
}
else {
if (pcode.value.match(numbers)){
return true;
}
}
}
function validatePhone(input) {
var phoneNo = /^\d{10}$/;
if (input.value.match(phoneNo)) {
return true;
} else {
alert("Phone number must be in the format of 04xxxxxxxx");
}
}
function validateEmail(input) {
var email = input.value;
if (email.indexOf("#") > -1 && email.indexOf(".") > -1) {
return true;
} else {
alert("Please enter a valid email address");
return false;
}
}
</script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<form id="regForm" name="regForm" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]); ?>" method="post" onsubmit="return confirmPword();">
<div id="header">
<h1>Western Sydney Hotel</h1>
</div>
<h1>Register as a User</h1>
<p> Please fill out the form below to register for the hotel website. </p>
<hr>
<h2>Account Details</h2>
<b>Username</b>
<input type= "text" name="uname" id="uname" size="20" maxlength="20" onblur="validateUsername(this);" value="<?php echo htmlspecialchars($username); ?>">
<br><br>
<b>Password</b>
<input type= "password" name="pword" id="pword" size="20" maxlength="20" min="6" onblur="validatePword(this);" value="<?php echo htmlspecialchars($pwrd); ?>">
<b>Retype password</b>
<input type= "password" name="pword2" id="pword2" size="20" maxlength="20" min="6" value="<?php echo htmlspecialchars($repwrd); ?>">
<br>
<hr>
<h2>Personal Details</h2>
<p>
<b>Title:</b>
<br>
<select name="Title" required>
<option value=" "></option>
<option value="Dr">Dr</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
</select>
</p>
<p><b>First Name:</b><br> <input type= "text" name="FName" id="FName" size="20" maxlength="20" onblur="validateName(this);" value="<?php echo htmlspecialchars($gname); ?>" /></p>
<p><b>Family Name:</b><br> <input type="text" name="LName" id="LName" size="20" maxlength="20" onblur="validateName(this);" value="<?php echo htmlspecialchars($sname); ?>" /></p>
<hr>
<h2>Contact Details</h2>
<p><b>Street Address:</b><br> <input type="Text" Name="add" id="add" size="40" maxlength="40" onblur="validateAdd(this);" value="<?php echo htmlspecialchars($addr); ?>" /></p>
<p><b>Suburb:</b><br> <input type="text" name ="Suburb" value="<?php echo htmlspecialchars($suburb); ?>" /></p>
<p><b>State:</b><br> <select name ="state" id="state" value="<?php echo htmlspecialchars($state); ?>" >
<option value=" "> </option>
<option value="nsw"> NSW </option>
<option value="wa"> WA </option>
<option value="sa"> SA </option>
<option value="vic"> VIC </option>
<option value="qld"> QLD </option>
<option value="nt"> NT </option>
<option value="act"> ACT </option>
</p>
</select>
<br>
<p><b>Country:</b><br> <input type="text" name ="country" /></p>
<p><b>Postcode:</b> <br><input type="Text" size="4" maxlength="4" name="pcode" id="pcode" onblur="validatePostcode(this);" value="<?php echo htmlspecialchars($ptcode); ?>"/> </p>
<p><b>Telephone:</b><br> <input type="Tel" name="Telephone" /></p>
<p><b>Mobile:</b><br> <input type="text" name="mobile" id="mobile" onblur="validatePhone(this);" value="<?php echo htmlspecialchars($mobile); ?>" /></p>
<p><b>Email:</b><br> <input type="Email" name="email" maxlength="40" onblur="validateEmail(this);" value="<?php echo htmlspecialchars($email); ?>" /></p>
<br>
<hr>
<input type="Submit" name="submit" value="Submit"/>
<input type="Reset" name ="reset" value="Reset"/>
<br>
<br>
<div id="footer">
Copyright © Western Sydney Hotels
</div>
</form>
<?php
require_once("dbconn.php");
if (isset($_POST["submit"]) && strlen($usernameErr)==0 && strlen($pwrdErr)==0 && strlen($repwrdErr)==0 && strlen($gnameErr)==0 && strlen($snameErr)==0
&& strlen($addrErr)==0 && strlen($stateErr)==0 && strlen($ptcodeErr)==0 && strlen($mobileErr)==0 && strlen($emailErr)==0)
{
$sql = "INSERT INTO customers(username, password, gname, sname, address, state, postcode, mobile, email)
VALUES ('$username', '$pwrd', '$gname', '$sname', '$addr', '$state', '$ptcode', '$mobile', '$email')";
if (mysqli_query($dbConn, $sql))
{
echo "Registration for Western Sydney Hotels complete";
header("location: customerlogin.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbConn);
}
}
mysqli_close($dbConn);
die();
?>
</body>
</HTML>

How to disable submit till only required fields are filled up

I have searched but I get info about how to disable submit button till all fields are completed....
I have following form where some fields are required and some are optional.
I want to disable submit button till required fields are completed.
sample code of form :
<form name="registration_form" id="registration_form" action="nextaction.php" method="post" enctype="multipart/form-data" >
Name : <input type="text" id="name" name="name" required>
Email : <input type="text" id="name" name="name" required>
Mobile : <input type="text" id="mobile" name="mobile" required>
Gender : <input type="text" id="gender" name="gender" >/*optional*/
Occupation : <input type="text" id="occupation" name="occupation" >/*optional*/
City : <input type="text" id="city" name="city" required>
Avatar : <input type="file" id="avatar" name="avatar" required>
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" />
===========
Edited
what I have tried for submit disable untill all field completed as follows :
First Thing :
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" disabled="disabled" />
script :
<script>
$(document).ready(function (){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
});
</script>
$('#registration_form input[required]').on('input propertychange paste change', function() {
var empty = $('#registration_form').find('input[required]').filter(function() {
return this.value == '';
});
$('#register').prop('disabled', (empty.length));
});
https://jsfiddle.net/ot5kn5c7/
This should work.
Anytime anything changes on any required input check for the count of required fields that are not empty. Once there are 0 required empty inputs update the disabled property for the button. (0 evaluates as false)
If you didn't to disable the button and wanted to only stop the form from submitting you would attach to the submit event on the form and just prevent the default action using similar logic checking the length.
$('form').on('submit', function(e) {
var empty = $(this).find('input[required]').filter(function() {
return this.value == '';
});
if (empty.length) {
e.preventDefault();
alert('enter all required field!')
}
});
Working solution for your case: https://jsfiddle.net/j9r5ejho/
$('form').submit(function(){
var valid = true;
$('input[required]').each(function(i, el){
if(valid && $(el).val()=='' ) valid = false;
})
return valid;
})
Untested but it should work with something like this:
(function() {
// whenever you type in a field
$('form > input').keyup(function() {
var empty = false;
// scan all fields in this form with the attribute required
$('form').find('input[required]').each(function() {
// if it's empty, cancel the loop
if ($(this).val() == '') {
empty = true;
return false;
}
});
// in case we have an empty required field,
// disable submit button
if (empty) {
$('input:submit').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})();
In order to prevent posting the form on a button or input type="submit", you can simply use e.preventDefault() which would prevent from proceeding with the default behavior.If you are using jquery validation and have a required attribute, you can just invoke $.validate() to validate the form.
$('input:submit').click(function(e)
{
if(!$.validate())
e.preventDefault();
});
example : https://jsfiddle.net/DinoMyte/suj951ga/1/
Just in case you want to try something like this. This won't disable the submit button but if you want to stop it from submitting until all required fields are fill in. This should work.
Not sure what database your using but this is for the PDO. You can just change the connection part to mysqli.
It won't submit to your database until you complete all the required fields and will also display the required input error messages.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white
space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success! Form Submitted!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Use this if you want to redirect it to another page so it won't send the form again to your PDO database if they refresh it.
It won't submit to your database and will stay on the HOME.PHP page until you complete all the required fields and will also display the required input error messages while on HOME.PHP page.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
Added a "header("Location: welcome.php");" after "$conn->exec($sql);"
HOME.PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
header("Location: welcome.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
WELCOME.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Success! Form Submitted!</h1>
<script type="text/javascript" src="js/main.js" ></script>
</body>
</html>

JavaScript/Jquery file not loading

My Jquery works fine in-line however when I try and make it external it doesn't seem to work.
I have both scripts stored in the: include('./includes/header.html');
And I also have them stored at the root of the folder.
If any one could help would be great.
I have two links held within the header.html
<!DOCTYPE html>
<head>
<title> <?php $page_title ?> </title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="formValidation.js"></script>
<script src="jquery-1.10.2.js"></script>
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Films.com</h1>
</div>
<div id="content">
<div id="nav">
<ul>
<li>Login</li>
<li>Home</li>
<li>Register</li>
<li>Film</li>
<li>Add a Film</li>
</ul>
</div>
When going to add_film.php the Jquery that would normally slide down my form, now it doesn't slide down.
<?php
include('./includes/header.html');
echo "<h1>Add A film</h1>";
if(isset($_POST['submitted'])){
$errors = array(); // Initialize erroy array.
// Check for title.
if (empty($_POST['movie_title'])){
$errors[] = "You forgot to enter a title.";
} else {
$mn = (trim($_POST['movie_title']));
}
// Check for leading actor
if (empty($_POST['leading_actor'])){
$errors[] = "You forgot to enter the leading actor.";
} else {
$la = (trim($_POST['leading_actor']));
}
// Check for a rating
if (empty($_POST['rating'])){
$errors[] = "Please select a rating.";
} else {
$rating = ($_POST['rating']);
}
// Check for a review
if (empty($_POST['review'])){
$errors[] = "Please write a review";
} else {
$review = (trim($_POST['review']));
}
if (empty($errors)) { // If no errors were found.
require_once('./includes/Mysql_connect.php');
// Make the insert query.
$query = "INSERT INTO films (movie_title, actor, rating)
Values ('$mn', '$la', '$rating' )";
$result = mysql_query($query);
$id = mysql_insert_id();
$query = "INSERT INTO reviewed (review, movie_id)
values ('$review', '$id')";
$result = mysql_query($query);
//Report errors.
} else {
foreach ($errors as $msg){
echo " - $msg <br/> ";
}
}
}
?>
<html>
<form action="add_film.php" method="post" id="add_film">
<fieldset>
<label for="title">Movie Title</label>
<input type="text" name="movie_title" id="movie_title" />
<br/>
<br/>
<label for="actor">Leading Actor</label>
<input type="text" name="leading_actor" id="leading_name" />
<br/>
<br/>
<label for="rating">Rating</label>
<select id="rating" name="rating"/>
<option selected="selected" value=0 disabled="disabled">Select a Rating</option>
<option value="Terrible">Terrible</option>
<option value="Fair">Fair</option>
<option value="Ok">Ok</option>
<option value="Good">Good</option>
<option value="Excellent">Excellent</option>
</select>
<br/>
<br/>
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="review" rows="15" cols="60"></textarea>
<br/>
<br/>
<input type="submit" name="submit" id="submit" value="submit" />
<input type="hidden" name="submitted" value="TRUE" />
</fieldset>
</form>
<br/>
</html>
<?php
include('./includes/footer.html');
?>
Here is my Jquery.
$(document).ready(function(){
$('#add_film').slideDown(800);
// Focus on first form field.
$("input:text:visible:first").focus();
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
if (error) {
e.preventDefault();
}
});
});
Change the order you load them:
<script src="jquery-1.10.2.js"></script>
<script src="formValidation.js"></script>
the order in which you load the scripts is important.
since your script uses jquery, so jquery needs to be loaded before your script.
so change the order of loading. first load jquery, then your script.
this is also the reason, why your script works inline.

Categories