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>
Related
i have created a registrartion form and connected it to mysql and data is sucessfully entered in tables in database now i want to add validations on form i have a file index.html in which i have a code of body of form and second file is connect.php where i have database connectivity code and validations code now when i run the program i can add data in form and its saved in database but validations code is not working
here is my code
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mail = $_POST['mail'];
$password = $_POST['password'];
$age = $_POST['age'];
$gender = $_POST['gender'];
//database Connection
$conn = new mysqli('localhost', 'root', '', 'codetodesign');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into registration(firstName, lastName, mail, password, age, gender)
values(?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssi",$firstname, $lastname, $mail, $password, $age, $gender);
$stmt->execute();
echo "Registration successfully";
$stmt->close();
$conn->close();
}
//Validation data
$firstnameErr = $lastnameErr = $mailErr = $passwordErr = $ageErr = $genderErr = "";
$firstname = $lastname = $mail = $password = $age = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["firstname"])){
$firstnameErr = "Firstname is required";
} else {
$firstname = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"])){
$lastnameErr = "lastname is required";
} else {
$lastname = test_input($_POST["lastname"]);
}
if (empty($_POST["mail"])){
$mailErr = "Mail is required";
} else {
$mail = test_input($_POST["mail"]);
}
if (empty($_POST["password"])){
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["age"])){
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
}
if (empty($_POST["gender"])){
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope you are enjoying your coding journey. Here I added some modification regarding your asking and approach.
Modifications:
We take an array variable named errors where we will store the errors
If we find any error we will store them in our errors variable
Then we will check the validation before we insert the data into database that errors array is empty or not
If errors is empty we simply store our data into database.
And if not we will catch all the errors from errors variable and will show those errors in our form(index.php) file.
Follow the below codes of two files hope rest of you understand easily.
Good Luck.
process.php
<?php
//database Connection
$conn = new mysqli('localhost', 'root', '', 'codetodesign');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//error array
$errors = array();
$success = null;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mail = $_POST['mail'];
$password = $_POST['password'];
$age = $_POST['age'];
$gender = $_POST['gender'];
if (empty($firstname)){
$errors['f_name'] = "Firstname is required";
} else {
$firstname = test_input($_POST["firstname"]);
}
if (empty($lastname)){
$errors['l_name'] = "lastname is required";
} else {
$lastname = test_input($_POST["lastname"]);
}
if (empty($mail)){
$errors['mail'] = "Mail is required";
} else {
$mail = test_input($_POST["mail"]);
}
if (empty($password)){
$errors['password'] = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($age)){
$errors['age'] = "Age is required";
} else {
$age = test_input($_POST["age"]);
}
if (empty($gender)){
$errors['gender'] = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if(!empty($errors)) {
$errors['msg'] = "Please fillup the below required fileds";
} else {
$stmt = $conn->prepare("insert into registration(firstName, lastName, mail, password, age, gender)
values(?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssi",$firstname, $lastname, $mail, $password, $age, $gender);
//$stmt->execute();
if($stmt->execute()) {
$success = "Registration successfully";
}
$stmt->close();
$conn->close();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
index.php
<?php include('process.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Test From</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container col-md-6">
<h1>Simple Form Registrarion</h1>
<h5 class="text-success"><?php if($success != null) echo $success; ?>
<h5 class="text-danger"><?php if(!empty($errors) && !empty($errors['msg'])) echo $errors['msg']; ?></h5>
<form action="index.php" method="POST">
<div class="form-group">
<label for="exampleInputfname">First Name</label>
<input type="text" name="firstname" class="form-control" id="exampleInputfname" aria-describedby="fnameHelp" placeholder="Enter First Name">
<small id="fnameHelp" class="form-text text-danger"><?php if(!empty($errors) && !empty($errors['f_name'])) echo $errors['f_name']; ?></small>
</div>
<div class="form-group">
<label for="exampleInputlname">Last Name address</label>
<input type="text" name="lastname" class="form-control" id="exampleInputlname" aria-describedby="lnameHelp" placeholder="Enter Last Name">
<small id="lnameHelp" class="form-text text-danger"><?php if(!empty($errors) && !empty($errors['l_name'])) echo $errors['l_name']; ?></small>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="mail" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-danger"><?php if(!empty($errors) && !empty($errors['mail'])) echo $errors['mail']; ?></small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password" aria-describedby="passHelp">
<small id="passHelp" class="form-text text-danger"><?php if(!empty($errors) && !empty($errors['password'])) echo $errors['password']; ?></small>
</div>
<div class="form-group">
<label for="exampleInputgender">Gender</label>
<div class="form-check">
<input class="form-check-input" name="gender" value="1" type="radio" name="exampleRadios" id="exampleRadios1" value="option1" checked>
<label class="form-check-label" for="exampleRadios1">
Male
</label>
</div>
<div class="form-check">
<input class="form-check-input" name="gender" value="2" type="radio" name="exampleRadios" id="exampleRadios2" value="option2">
<label class="form-check-label" for="exampleRadios2">
Female
</label>
</div>
<div class="form-check">
<input class="form-check-input" name="gender" value="3" type="radio" name="exampleRadios" id="exampleRadios2" value="option2">
<label class="form-check-label" for="exampleRadios2">
Other
</label>
</div>
</div>
<div class="form-group">
<label for="exampleInputage">Age</label>
<input type="number" name="age" class="form-control" id="exampleInputage" aria-describedby="emailHelp" placeholder="Enter age">
<small id="emailHelp" class="form-text text-danger"><?php if(!empty($errors) && !empty($errors['age'])) echo $errors['age']; ?></small>
</div>
<button type="submit" name="register" class="btn btn-primary">Register</button>
</form>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</html>
I'm currently writing a script that preforms basic user registration.
When the user arrives on the landing page, I have a JS script that identifies their email from the URL and fills it in the email input box (which is disabled). After, the user just needs to put in their password to create an account. However, PHP throws the error "Email is required" even though it's been filled by the JS script.
I've tried to change the status of the input box to disabled to enabled which doesn't do much to help. I've attached the files involved in the process below. Any help would be greatly appreciated.
fillEmail.js
$(document).ready(function() {
var link = window.location.href;
var emailIndex = link.indexOf("email");
if(emailIndex != -1) {
link = link.substring(emailIndex + 6);
} else {
link = "";
}
document.getElementById("email").value = link;
//$('#email').attr('disabled', 'disabled');});
register.php
<?php include('server.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div hidden class="input-group">
<label>Username</label>
<input type="text" name="username" value="user">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" id="email" value="<?php echo $email; ?>" disabled>
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
</form>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous">
</script>
<script type='text/javascript' src="fillEmail.js"></script>
</html>
server.php
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
?>
I'm fairly new to PHP so any help would be greatly appreciated. Thanks so much in advance!
As per my comment, you can simply use readonly instead of disabled to achieve a similar effect. Also please use prepared statements to protect against SQL injection. mysqli_real_escape_string is not enough
In order for the value to be submitted the field cannot be disabled.
Simple solution, create another fields as (hidden), these are submitted
<input type="email" id="email" value="<?php echo $email; ?>" disabled>
<input type="hidden" name="email" value="<?php echo $email; ?>">
Or you could simply change the attribute from disables to readonly
I want to create a form where the submit button is disabled until the form is ready to be submitted. Not only does the form need to be filled in, but certain parameters need to be met. Passwords must match. Email must be valid and not already be in the database. A radio button must be selected. How can I send the values from all inputs at the same time on every upkey.
Here's my index.php file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
function validate_form(value){
$.post("validate_form.php",{first_name:value},function(data){
if (data=="Available"){
document.getElementById("mySubmit").disabled = false;
} else {
document.getElementById("mySubmit").disabled = true;
}
});
};
</script>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="first_name" placeholder="First Name" onkeyup="validate_form(first_name.value)"><br>
<input type="text" name="last_name" placeholder="Last Name"><br>
<input type="text" name="email" placeholder="Email"><br>
<input type="password" name="password" placeholder="Password"><br>
<input type="password" name="password_repeat" placeholder="Re-enter Password"><br>
<input type="radio" name="choice" value="Y" id="yes">Yes
<input type="radio" name="choice" value="N" id="no">No
<br>
<input type="submit" name="submit" value="Sign Up" disabled id="mySubmit">
</form>
</body>
</html>
and here's my validate_form.php file
<?php
$first_name = "";
$last_name = "";
$email = "";
$password = "";
$password_repeat = "";
$answer = "";
$go = array(0,0,0,0,0);
if(isset($_POST['first_name'])){$first_name = $_POST['first_name'];}
if(isset($_POST['last_name'])){$last_name = $_POST['last_name'];}
if(isset($_POST['email'])){$email = $_POST['email'];}
if(isset($_POST['password'])){$password = $_POST['password'];}
if(isset($_POST['password_repeat'])){$password_repeat = $_POST['password_repeat'];}
if(isset($_POST['choice'])){$answer = $_POST['answer'];}
//Does email already exist in database
mysql_connect("localhost", "root", "password") or die (mysql_error ());
mysql_select_db("database") or die(mysql_error());
$strSQL = "SELECT * FROM users";
$loop = mysql_query($strSQL);
$email_exists = 0;
while($row = mysql_fetch_array($loop)) {
if($row['email'] == $email){
$email_exists = 1;
}
}
//Is email valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$email_valid = 1;
} else {
$email_valid = 0;
}
//Check each parameter
if(strlen($first_name) > 0){
$go[0] = 1;
}
if(strlen($last_name) > 0){
$go[1] = 1;
}
if($email_exists != 1 and $email_valid == 1){
$go[2] = 1;
}
if(strlen($password) > 6 and $password == $password_repeat){
$go[3] = 1;
}
if($answer != ""){
$go[4] = 1;
}
if(array_sum($go) == 5){
echo "Available";
} else {
echo "Form is not viable";
}
?>
I currently have it send $first_name to validate_form.php, but I'm not sure how to send all variables at once. Any help would be awesome.
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;
if user want to submit their form, they have to checked the terma and condition box first.
so where should i add the code?
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = "";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</form>
</fieldset>
</form>
</div>
</body>
</html>
and so here is my userdetail.php to get user data...
<?php
session_start();
$forename = $_SESSION['forename'];
$surname = $_SESSION['surname'];
$email = $_SESSION['email'];
$postalAddress = $_SESSION['postalAddress'];
$landLineTelNo = $_SESSION['landLineTelNo'];
$mobileTelNo = $_SESSION['mobileTelNo'];
$sendMethod = $_SESSION['sendMethod'];
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
if($_SESSION['postalAddress']==NULL)
{echo "<p>postalAddress:NULL</p>";}
else {echo "<p>PostalAddress : $postalAddress </p>";}
if($_SESSION['email']==NULL)
{echo "<p>email:NULL<p/>";}
else {echo "<p>email : $email</p>";}
if($_SESSION['landLineTelNo']==NULL)
{echo "<p>landLineTelNo:NULL<p/>";}
else {echo "<p>landLineTelNo : $landLineTelNo </p>";}
if($_SESSION['mobileTelNo']==NULL)
{echo "<p>mobileTelNo:NULL<p/>";}
else {echo "<p>mobileTelNo : $mobileTelNo </p>";}
echo "<p>sendMethod : $sendMethod </p>";
?>
i need the term and condition check box to be checked else use cannot submit the form....
REMEMBER! Using javascript will just make it easy for user.It prevents loading another page to display error. STILL if a browser has javascript turned of it will pass the checked Terms without even checking it. so you should Always check it serverside (PHP) and use javascript for users ease.
in your HTML:
<form id="userdetail" ....>
...
<input type="checkbox" name="terms" id="terms" value="accepted" />
...
</form>
then in your javascript:
Pure JS:
document.getElementById('userdetail').addEventListener('submit', function(event){
if(document.getElementById('terms').checked == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
Using JQuery (jquery.com)
$('#userdetail').submit(function(event){
if($('#terms').is(':checked') == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
and in your PHP to check if it is checked you should use
if(isset($_POST['terms']) && $_POST['terms'] == 'accepted') {
// Continue Registring
} else {
// Display Error
}
Instead of submit you do:
<input type="button" onclick="javascript:myFunction()" Value="Submit">
And then the javascript function:
function myFunction() {
if(document.getElementById("terms").checked == true){
document.getElementById("userdetail").submit();
}
else{
alert("You have to agree on terms and conditions");
}
}
In Jquery you can do like below:
<script>
$('#userdetail').submit(function(){
if($('#terms').is(':checked'))
{
return true;
}
else
{
return false;
}
});
</script>
Replace the part of html with the given html in answer and add the function below to you script...
function verify_terms()
{
if (!$('#terms').is(':checked'))
{
alert('Please agree terms and conditions');
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" onclick="return verify_terms();" value="submit" />