HTML form submit button check - php

I have created an HTML form that stores data in a database and later on I take them, and today I wanted to make it more advanced.
I have a form that looks like this (not for login, just for example)
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name"/>
Surname: <input type="text" name="surname" />
Phone: <input type="text" name="phone" />
<input type="submit" />
In process.php, it stores data in the database so later I can use them.
I want to make it so if one or more of them are empty, when you press submit button it shows error like "Must fill all fields", but if you have done everything, it just submits and stores data in database.
I thought I can make with this kind of code:
<?php
$required = array('name', 'surname', 'phone');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
Write an error message and don't react to submit
}
else {
If everything is done, allow to submit
}
?>
How can I make it work, so that you can't press Submit while you haven't finished all fields?

You're wanting something client side to validate the fields before you're able to submit to the next page. Look up validation in jQuery and maybe include the "required" attribute that's been added into HTML5.

Add name attribute to button set required to all required fields
<input name="submit" type="submit" />
in php
<?php
if(isset($_POST['submit'])){
$required = array('name', 'surname', 'phone');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
write and error message and don't react to submit
} else {
if everything is done, allow to submit
}
}
?>

Try the below code
<?php
if(isset($_POST['submit'])){
$required = array('name', 'surname', 'phone');
$error = false;
$message='';
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
$message = 'All fields required';
}else{
//Submit process here
}
}
?>
<?php echo $message; ?>
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name"/>
Surname: <input type="text" name="surname" />
Phone: <input type="text" name="phone" />
<input type="submit" name="submit" value="Submit" />

Easiest and quickest way, You can use HTML5 required.
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name" required />
<BR>
Surname: <input type="text" name="surname" required />
<BR>
Phone: <input type="text" name="phone" required />
<BR>
Gender: Male <input type="radio" name="gender" value="1" required />
Female <input type="radio" name="gender" value="2" required />
<BR>
<input type="submit" />
</form>

Related

checking users html form info with PHP on same page

I am trying to write a simple html form which requires the user to enter the correct email and password, using $_SERVER as the action for my form. I do not want to send the POST info to another php page, but I want to do it on the same page instead.
I have set two variables, $correct_email and $correct_password.
Here is the form;
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="eml">Email:</label>
<input type="email" name="eml" id="eml" required>
<br>
<label for="pwd">Password:</label>
<input type="password" name="pwd" id="pwd" required>
<br>
<input type="hidden" name="checkMe" value="12345">
<input type="submit" name="submit" value="Submit">
</form>
Here is what I am trying to get work in PHP
$correct_email = "(my personal email)";
$correct_password = "password"];
if ($_POST['eml']) == $correct_email && ($_POST['pwd']) == $correct_password {
echo "<h1>You are logged in</h1>";
} else {
echo "<h1>error</h1>";
}
It is not working, please help! I am also unclear on whether the PHP should come before or after the form.
Also, I would like to have the form be cleared from view, on the page, when the correct info is entered.
Thanks so much
Change the name of the submit button - never call anything "submit" in a form
Put the test at the top
You had issues with the ( and ) in the test
Also an issue with a ] after "password"
<?php
if ($_POST["subBut"] === "Submit") {
$correct_email = "(my personal email)";
$correct_password = "password";
if ($_POST['eml'] == $correct_email && $_POST['pwd'] == $correct_password) {
echo "<h1>You are logged in</h1>";
} else {
echo "<h1>error</h1>";
}
}
else {
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]); ?>">
<label for="eml">Email:</label>
<input type="email" name="eml" id="eml" required>
<br>
<label for="pwd">Password:</label>
<input type="password" name="pwd" id="pwd" required>
<br>
<input type="hidden" name="checkMe" value="12345">
<input type="submit" name="subBut" value="Submit">
</form>
<?php } ?>

simple form in angularjs php

My form code is
<form name="myForm" ng-controller="Ctrl" action="form.php" method="POST">
Name: <input name="input" ng-model="userName" name="name" required placeholder="Enter Name"><br>
Email: <input name="email" ng-model="userEmail" name="email" required placeholder="Enter Email"><br>
<input type="submit" name="submit"><br>
<tt>userType = {{userName}}</tt><br>
<tt>userEmail = {{userEmail}}</tt><br>
</form>
My script is
<script >
function Ctrl($scope) {
$scope.userName = '';
$scope.userEmail = '';
}
</script>
form.php code is
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$email = $_POST['email'];
echo $name."<br>";
echo $email."<br>";
}
how to pass form value to php , any idea
I would prefer to keep my model inside an object:
here is a plunker: http://plnkr.co/edit/fC1GikCS0v1tDVTG37vZ?p=preview
controller
function Ctrl($scope, $http) {
$scope.user = {
name : '',
email: ''
};
$scope.submit = function(user){
$http.post('/form.php', user);
}
}
html
<form name="myForm" ng-controller="Ctrl" ng-submit="submit(user)">
Name: <input type="text" ng-model="user.name"><br>
Email: <input type="email" ng-model="user.email"><br>
<input type="submit" name="submit"><br>
</form>
in ur code above u used name tag twice..
thats y in php code it was not picking up the data.

if there is no post data redirect back to the registration page

I have a form:
<form id='register' action='http://mydev/test/register' onsubmit="return validateForm()" method='post' accept-charset='UTF-8'>
<fieldset>
<legend><br/>Create An Account</legend><br/>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<!--<label for='username' >Username*: </label>
<input type='text' name='username' id='username' maxlength="50" /><br/><br/></br/>-->
<label for='email' >Email Address*:</label>
<input type='text' name='email' id='email' maxlength="50" /><br/><br/>
<label for='password'>Password:</label>
<input type="password" name="password" id="password" value="" size="32" /><br><br>
<label for='retype_password'>Re-Enter Password:</label>
<input type="password" name="password-check" id="password-check" value="" size="32" /><br><br>
<label for='cpassword' >‌</label>
<input type="submit" value="Submit" id="submit">
</fieldset>
</form>
I than have my action page which sends an activation link to their email:
$shopper = new Shopper();
$shopper->set_email($_POST['email']);
$shopper->set_username($_POST['email']);
if($shopper->create($_POST['password']))
{
$message = "<br>User created<br>" . "An activation code has been sent<br>";
$token = $shopper->request_activation();
}
else
{
$message = "Could not create user<br>";
}
My question is... if there is no post data and they somehow end up on the register.php page.. just redirect them back to the new_registration.php page.
I know I should user header("location:../../new_registration.php");
I'm just a bit confused on how to check for the missing post data?
Should i be using empty?
I ended up using:
if (empty($_POST['email']['password'])) {
header('location:http://myjeromesdev/test/new_registration');
}
else {
$shopper = new Shopper();
$shopper->set_email($_POST['email']);
$shopper->set_username($_POST['email']);
if($shopper->create($_POST['password']))
{
$message = "<br>User created<br>" . "An activation code has been sent<br>";
$token = $shopper->request_activation();
}
else
{
$message = "Could not create user<br>";
}
}
?>
<p>
<?php
echo $message
?></p>
Yes, you can use empty, but also you should check if the received $_POST data is what you are waiting for.
if(!empty($_POST['email']) && !empty($_POST['password']))
{
$shopper = new Shopper();
$shopper->set_email($_POST['email']);
$shopper->set_username($_POST['email']);
...
}
else
{
//Your redirect
}
u can use isset and set name at submit (not set name is also ok) u can use one name of you input
see this code
<input type="submit" name="submit" value="submit"/>
if(isset($_POST['submit'])){
//code is have
}else{
header('URL');
}
if you want if all post is setted u can use AND
isset($_POST['password']) && isset($_POST['email']) and so on
hope this answer help you

Why is my form submitting too early?

I have a form on one page, and the submit button on that page leads the user to the next page of the form. I'm trying to set it up so that the info from form 1 is submitted along with form 2's info when the submit button on form 2 is clicked and all forms have been filled out, however, the first form's data is being submitted to my database when proceeding to form 2. Any ideas why this is the case? And any ideas of a solution?
Also, I am getting an error "undefined index GET" from the first form and I am struggling to understand why?
Thanks in advance!
Form 1 (parent.php)
<?php session_start();
$_SESSION['fName']=$GET['fName'];
$_SESSION['sName']=$GET['sName'];
$_SESSION['email']=$GET['email'];
$_SESSION['address']=$GET['address'];
?>
<!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=iso-8859-1″ />
<title>table2</title>
</head>
<h1>Is this in xamppfiles and htdocs?</h1>
<form action="child2.php" method="post" class="validate">
<div>
<input class="tb" type="text" name="fName" placeholder="first name" id="fName" value=" <?php $fName ?>" required/><br/>
<br/>
<input class="tb" type="text" name="sName" placeholder="surname" id="sName" value="<?php $sName ?>" required/><br/>
<br/>
<input class="tb" type="email" name="email" required placeholder="email address" id="email" value="<?php $email ?>" required/>
<br/>
<input class="tb" type="address" name="address" placeholder="address" value="<?php $address ?>" id="address" />
<br/>
<input id="submit" name="submit" type="submit" value="Next">
</div>
</form>
</body>
</html>
Form 2 (child2.php)
<?php
session_start();
include("connect.php");
?>
<!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=iso-8859-1″ />
<title>table2</title>
</head>
<body>
<?php
function renderForm($fName, $sName, $email, $address){
?>
<form action="" method="post" class="validate">
<label class="label">first name</label><input class="tb" type="text" id="fName" name="fName" value="<?php if (isset($fName)) { echo $fName = $_SESSION['fName'];} else { if(!isset($fName)) { echo ""; }}?>"/>
</br>
<label class="label">surname</label><input class="tb" type="text" id="sName" name="sName" value="<?php if (isset($sName)) { echo $sName = $_SESSION['sName'];} else { if(!isset($sName)) { echo ""; }}?>"/>
</br>
<label class="label">email</label><input class="tb" type="email" id="email" name="email" value="<?php if (isset($email)) { echo $email = $_SESSION['email'];} else { if(!isset($email)) { echo ""; }}?>""/>
</br>
<label class="label">address</label><input class="tb" type="text" id="address" name="address" value="<?php if (isset($address)) { echo $address = $_SESSION['address'];} else { if(!isset($address)) { echo ""; }}?>""/>
</br>
<input id="submit" type="submit" value="Submit"/>
</form>
<?php
}
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$fName = mysql_real_escape_string(htmlspecialchars($_POST['fName']));
$sName = mysql_real_escape_string(htmlspecialchars($_POST['sName']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$address = mysql_real_escape_string(htmlspecialchars($_POST['address']));
// check to make sure both fields are entered
if ($fName == '' || $sName == '' || $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($fName, $sName, $email, $address, $error);
}
else
{
// save the data to the database
mysql_query("INSERT formtest SET fName='$fName', sName='$sName',email='$email', address='$address'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: child2.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','','');
}
?>
</body>
</html>
The action field of your parent.php is child2.php . Also, you are checking for
if (isset($_POST['submit']))
which is set true by your first page, hence, it goes inside the loop and inserts the data in your database. This can be resolved by placing this in your parent file
<input id="submit" name="submitINIT" type="submit" value="Next">
A possible solution can be, you extract the values of the first form and store it in some session variables , and finally at final submission, you can use those values for insertion.
In your child2.php, do this
if (isset($_POST['submitINIT'])){
// store all the available values in some session variables
$_SESSION['value1']=$POST['fName'];
$_SESSION['value2']=$POST['sName'];
$_SESSION['value3']=$POST['email'];
$_SESSION['value4']=$POST['address'];
}
if (isset($_POST['submit'])){
// proceed after final submission
}
Also, change the action of 2nd file to itself using this
<form action="child2.php" method="post" class="validate">
Also, do this modification in your child2.php
<input id="submit" name="submit" type="submit" value="Submit"/>

Call a PHP function after onClick HTML event

Purpose:
Call a PHP function to read data from a file and rewrite it. I used PHP only for this purpose - FileIO - and I'm new to PHP.
Solution?
I tried through many forums and knew that we cannot achieve it normal way: onClick event > call function. How can we do it, are there other ways, particularly in my case?
My HTML code and PHP code is on the same page: Admin.php.
This is HTML part:
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
This is PHP part:
function saveContact()
{
$datafile = fopen ("data/data.json", "a+");
if(!$datafile){
echo "<script>alert('Data not existed!')</script>";
}
else{
...
$contact_list = $contact_list . addNewContact();
...
file_put_contents("data/data.json", $contact_list);
}
fclose($datafile);
}
function addNewContact()
{
$new = '{';
$new = $new . '"fullname":"' . $_GET['fullname'] . '",';
$new = $new . '"email":"' . $_GET['email'] . '",';
$new = $new . '"phone":"' . $_GET['phone'] . '",';
$new = $new . '}';
return $new;
}
Have a look at these code, I want to call saveContact when people click on Add Contact button. We can reload page if need so. FYI, I use JQuery, HTML5 in page as well.
Thanks,
There are two ways. the first is to completely refresh the page using typical form submission
//your_page.php
<?php
$saveSuccess = null;
$saveMessage = null;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array(
'fullname' = $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
// always return true if you save the contact data ok or false if it fails
if(($saveSuccess = saveContact($data)) {
$saveMessage = 'Your submission has been saved!';
} else {
$saveMessage = 'There was a problem saving your submission.';
}
}
?>
<!-- your other html -->
<?php if($saveSuccess !== null): ?>
<p class="flash_message"><?php echo $saveMessage ?></p>
<?php endif; ?>
<form action="your_page.php" method="post">
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<!-- the rest of your HTML -->
The second way would be to use AJAX. to do that youll want to completely seprate the form processing into a separate file:
// process.php
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array(
'fullname' => $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
// always return true if you save the contact data ok or false if it fails
$response['status'] = saveContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
header('Content-type: application/json');
echo json_encode($response);
exit;
}
?>
And then in your html/js
<form id="add_contact" action="process.php" method="post">
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input id="add_contact_submit" type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<script type="text/javascript">
$(function(){
$('#add_contact_submit').click(function(e){
e.preventDefault();
$form = $(this).closest('form');
// if you need to then wrap this ajax call in conditional logic
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
dataType: 'json',
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},
error: function() {
$form.before("<p>There was an error processing your request.</p>");
}
});
});
});
</script>
<div id="sample"></div>
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<script>
$(document).ready(function(){
$("#submitButton").click(function(){
$("#sample").load(filenameofyourfunction?the the variable you need);
});
});
</script>
You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:
<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
{
$new = '{';
$new .= '"fullname":"' . $_GET['fullname'] . '",';
$new .= '"email":"' . $_GET['email'] . '",';
$new .= '"phone":"' . $_GET['phone'] . '",';
$new .= '}';
return $new;
}
function saveContact()
{
$datafile = fopen ("data/data.json", "a+");
if(!$datafile){
echo "<script>alert('Data not existed!')</script>";
}
else{
$contact_list = $contact_list . addNewContact();
file_put_contents("data/data.json", $contact_list);
}
fclose($datafile);
}
// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled
{ ?>
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact"/>
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->
Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...
Other thought, IE doesn't support placeholder.
cell1.innerHTML="<?php echo $customerDESC; ?>";
cell2.innerHTML="<?php echo $comm; ?>";
cell3.innerHTML="<?php echo $expressFEE; ?>";
cell4.innerHTML="<?php echo $totao_unit_price; ?>";
it is working like a charm, the javascript is inside a php while loop

Categories