Bootstrap form not passing value to php - php

I cannot understand why the input field "name" is not being passed to PHP. I tried commenting out the "name" code, but the same problem occurred with "company". I am setting the id and name properties on both input tags.
Revised
website example
HTML
<form name="createAccount" role="form" method="POST" action="php/AddNewAccount.php" >
<div data-toggle="buttons">
<div class="btn-group">
<label class="btn btn-primary">
<input type="radio" name="user-type" id="writer" value="writer" class="sr-only" required >Writer
</label>
<label class="btn btn-primary">
<input type="radio" name="user-type" id="enabler" value="enabler" class="sr-only" required>Enabler
</label>
</div>
</div><br/>
<div class="form-group">
<label for="name">Name:</label>
<input class="form-control" required id="name" name="name">
</div>
<div class="form-group">
<label for="company">Company:</label>
<input class="form-control" required id="company" name="company">
</div>
...
</form>
PHP
function AddNewAccount() {
try {
$acctType = $_POST["user-type"];
if (!isset($acctType) || empty(trim($acctType))) {
throw new Exception('You must select an account type."');
};
echo "account-type=" . $acctType;
$name = $_POST["name"];
if (!isset($name) || empty(trim($name))) {
throw new Exception('You must enter your name."');
};
$company = $_POST["company"];
if (!isset($company) || empty(trim($company))) {
throw new Exception('You must enter your company name."');
};
...
}
Error
[03-May-2016 21:41:44 UTC] PHP Fatal error: Uncaught exception
'Exception' with message 'You must enter your company name."' in
/home/deje/public_html/writers-tryst/php/AddNewAccount.php:18
Note the "user-type" is being passed correctly.

From what I see; your Code should work... I couldn't spot any errors, though. But, Why do you have an extra (") within your Exception Message? Are you using any Javascript on the Page? If Yes; I'd suggest you disable Javascript Temporarily and try sending the Form again without JS.
Could you try this instead?
function AddNewAccount() {
// IT MIGHT BE A GOOD IDEA (IF YOU WILL) TO DUMP THE ENTIRE $_POST GLOBAL VARIABLE
// AND END THE SCRIPT...(TEMPORARILY)... JUST TO SEE WHAT COMES BACK
// var_dump($_POST); exit; // BYPASSTHE DUMPING SINCE WE ARE SURE COMPANY MAKES IT THROUGH TO THIS POINT...
try {
$name = isset($_POST["name"]) ? htmlspecialchars(trim($_POST["name"])) : null;
$company = isset($_POST["company"]) ? htmlspecialchars(trim($_POST["company"])) : null;
$acctType = isset($_POST["user-type"]) ? htmlspecialchars(trim($_POST["user-type"])) : null;
if (!$acctType) {
throw new Exception('You must select an account type.');
}
if (!$name) {
throw new Exception('You must enter your name.');
}
if (!$company) {
throw new Exception('You must enter your company name.');
}
...
}
This the Result from the var_dump($_POST) on your App.
As you can see, Your code is still consistent and you now have the Company in the list of your Data.... so you may want to comment out the var_dump(); exit; part
<?php
//....PREVIOUS CODE
// var_dump($_POST); exit; //NOW COMMENTED OUT TO CONTINUE WITH THE PROGRAM
Try this and let's know how it goes...
I sincerely hope it goes well with you Now, though ;-)

Try the following:
<form name="createAccount" role="form" method="POST" action="php/AddNewAccount.php" enctype="application/x-www-form-urlencoded">
You can also parse it as a JSON:
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

Believe it or not, the problem was with the input tags ending in ">" instead of "/>". I have been testing in Chrome. I tested in IE now and it works there too. Thanks for everyone's input.

Related

How to pass and put variable from a php page into a another page(form)?

I working on two pages, a first one which has a form with three fields: name, email and message). This page will send these data to a second page, that will validate if those fields meet the criteria.
If on the second page, any of those fields does not meet the criteria, I want to redirect to the first page (or a third php one), fill the form with previous information and tell the user to correct the fields properly.
I'm strugling to send the data form the second page to the first (or third) one. Does anyone knows a good way to do it?
Here's my code:
First page - contato.html
<form action="validate.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" id="name" name="nome" placeholder="Type your name">
</div>
<div class="form-group">
<input type="text" id="email" name="email" placeholder="type your#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="Leave your message." ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send message" onclick="alert('Thank you!')" ></form>
Second Page - validate.php
if(isset($_POST['nome'])) $nome = $_POST['nome'];
if(isset($_POST['email'])) $email_visitante = $_POST['email'];
if(isset($_POST['mensagem'])) $mensagem = $_POST['mensagem'];
// if does not meet the criteria, redirect to contato.html and update the form with the info
if(empty($nome)){
Header("location:contato.html");
}
if(empty($email_visitante)){
Header("location:contato.html");
}
if(empty($mensagem)){
Header("location:contato.html");
}
// check for letters and space only
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
Header("location:contato.html");
}
// check if e-mail address is well-formed
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
Header("location:contato.php");
}
Does anyone knows how to do it? Either sending to a third page or redirecting to the first one (and fill the form in again)
You have to use sessions and store data there in one page and access in another, here is a small usage
<?php
// page 1
session_start();
// Set session variables
$_SESSION["nome"] = $nome;
$_SESSION["email"] = $email_visitante;
$_SESSION["mensagem"] = $mensagem;
<?php
// page 2|3|N - any other page
session_start();
// Get session variables
$nome = $_SESSION["nome"];
$email_visitante = $_SESSION["email"];
$mensagem = $_SESSION["mensagem"];
Part of your problem is that upon any failed validation you are using a redirect. Alternatively you can display an error message to the user: suggesting they need to correct their input by going back a page (browser back).
When forms get longer users need some hand holding with error correction. Their errors need to be clearly indicated with a message alongside as to how they can fix it.
Avoiding using the 'browser back' method above it's common to have the form send to its own url. I've included an example below.
By doing this you can repopulate the form with posted values upon error and add error feedback. You must be careful to escape user input in this situation.
I've added a generic error feedback notice. Which isn't that helpful in its current form. You could improve upon this by adjusting the validation code to return an array of error notices and use that within your form for more targeted error feedback. You could also add - all fields are required - text to help the user.
Upon successful validation that's when to redirect the user to a confirmation page. This can prevent form resubmissions.
Your name regex pattern in its current form will not allow hyphens or apostrophes. I haven't changed it below. Do bear this in mind. "Michael O'leary" would be faced with an error and likely not understand why. You need to be careful when using strict rules for user input. Also this will reject some unicode.
You also need to escape user input appropriately. Note that you may be satisfied that the name and email after validation follows a particular pattern, but becareful of raw user input. The message text is passed on raw after validation.
<?php
$nome = $_POST['nome'] ?? null;
$email_visitante = $_POST['email'] ?? null;
$mensagem = $_POST['mensagem'] ?? null;
$feedback = null;
if(isset($_POST['submit'])) {
if(validate($nome, $email_visitante, $mensagem) !== false) {
process($nome, $email_visitante, $mensagem);
// Redirect to success/thankyou/confirmation page.
header('location:success.html');
exit;
}
// This is a generic message, could this be more helpful?
$feedback = 'Your form has errors. Please correct them.';
}
form($nome, $email_visitante, $mensagem, $feedback);
function process($nome, $email_visitante, $mensagem) {
// do something with your values.
}
function validate($nome, $email_visitante, $mensagem) {
if(empty($nome)) {
return false;
}
if(empty($email_visitante)){
return false;
}
if(empty($mensagem)){
return false;
}
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
return false;
}
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
return false;
}
return true;
}
function form($nome = null, $email_visitante = null, $mensagem = null, $feedback = null) {
?>
<?= $feedback ?>
<form action='' method='POST' name='emailform'>
<div class='form-group'>
<label for='name'>Your name:</label>
<input type='text' id='name' name='nome' value='<?= htmlspecialchars($nome) ?>'>
</div>
<div class='form-group'>
<label for='email'>Your email address:</label>
<input type='text' id='email' name='email' value='<?= htmlspecialchars($email_visitante) ?>'>
</div>
<div class='form-group'>
<label for='message'>Your message:</label>
<textarea class='form-control' cols='30' rows='10' maxlength='300' id='message' name='mensagem'><?= htmlspecialchars($mensagem) ?></textarea>
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Send message'>
</div>
</form>
<?php
}

Problems with contact form functionality in php

Before You read the code, I have tried separating each part into their own php files and just using requires to fetch the code, but using requires or having all the code in the same file I seem to be getting the same errors regardless. I think it may have something to do with the the version of PHP I'm using.
I seem to be getting an error with submit on line 3 of the BACKEND part. Being an undefined property.
The second is an undefined error on the USER FEEDBACK section.
I've used this template before and has worked successfully.
I'm running PHP 5.4.12 and Apache 2.4.4 using WAMP on my Windows 8.1 Pro PC.
Any help would be appreciated
/** BACKEND **/
<?php
if($_POST['submit'])
{
$fName=$_POST['fName'];
$topic=$_POST['topic'];
$email=$_POST['email'];
$message=$_POST['message'];
function verify_email($email)
{
if(!preg_match('/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*#[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/',$email))
{
return false;
}
else
{
return $email;
}
}
function verify_email_dns($email)
{
list($name, $domain) = split('#',$email);
if(!checkdnsrr($domain,'MX'))
{
return false;
}
else
{
return $email;
}
}
if(verify_email($email))
{
if(verify_email_dns($email))
{
if ($fName=='')
{
header('location:./contact.php?error=missing');
}
elseif ($email=='')
{
header('location:./contact.php?error=missing');
}
elseif ($message=='')
{
header('location:./contact.php?error=missing');
}
else
{
foreach ($myvars as $var)
{
if (isset($_POST[$var]))
{
$var=$_POST[$var];
}
}
$subject = "Email Submission for review";
$add.="test.email#gmail.com";
$msg.="First Name: \t$fName\n";
$msg.="Email: \t$email\n";
$msg.="Topic: \t$topic\n";
$msg.="Message: \t$message\n";
$mailheaders="From: $email\n";
$mailheaders.="Reply-To: $email\n";
mail("$add", "$subject", $msg, $mailheaders);
header('location:./contact.php?error=none');
}//end else
}//end inner-if
else
{
header('location:./contact.php?error=mx');
}
}// end outter-if
else
{
header('location:./contact.php?error=format');
}
}// end starting if
/** VIEW for form **/
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactForm">
<label for="fName" class="first-name">Name:</label>
<input type="text" name="fName" value="" id="fName">
<br><br>
<label for="email" class="email-name">Email:</label>
<input type="text" name="email" value="" id="email">
<br><br>
<label for="topic" class="subject-name">Subject:</label>
<input type="text" name="topic" value="" id="topicsubject">
<br><br>
<label for="message" class="message-name">Message:</label>
<textarea name="message" rows="5" cols="60" id="message"></textarea>
<br><br>
<input type="submit" name="submit" id="submit-btn" class="submit-btn" value="Email Me">
</form>
/** USER FEEDBACK if error occurs **/
<?php
$error=$_GET['error'];
switch ($error)
{
case "mx":
echo "<br><span class='red'>Your email address you entered is invalid. Please try again.</span><br>";
break;
case "format":
echo "<br><span class='red'>Your email address is not in the correct format, it should look like name#domain.com. Please try again.</span><br>";
break;
case "missing":
echo "<br><span class='red'>You seem to be missing a required field, please try again.</span><br>";
break;
case "none":
echo "<br>Your email was sent. I will get back to you as soon as I can. Thank you for your interest.<br>";
break;
default:
echo "<br><br>";
}
?>
You are assuming that there are POST and GET variables when you are visiting the page. So its possible that $_POST['submit'] only exists when you actually submit the form otherwise you will get an error when first visiting that page.
try this condition instead:
if(isset($_POST['submit']) ) {
// now its safe to do something
}
You should never assume that any $_POST or $_GET variable is available when visiting the page.
Also off topic:
In your HTML you are using an 'action' attribute with the same url as the page you are visiting on this line here:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactForm">
Basically if you just leave out the action attribute all together it will have the same effect and its also semantic to do so. This is a better way of doing it and it has the same effect:
<form method="post" name="contactForm">
You can check this previous Stack Overflow question for a better explanation on that matter:
Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

PHP: Refresh page on invalid form submit

How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}

How to stop php from executing the script if form POST is empty?

I have two input fields and whenever I open my page, it displays errors since at the start user has not entered any input to any of the field (& the errors are displayed because the user input is used in sql queries to retrieve data).
I just want to display those two forms at start of the page not the errors.
Both inputs are required to execute the Compare button. If user has not entered either one of the inputs it should not send request to php for scripting.
I mean the Compare button should send request only if both inputs are filled otherwise it should give a message to user to Type the required fields.
How to do this?
$trimUser= trim ($_POST['name']);
if(empty($name) || empty($name2))
{
echo "Enter a name ";
}
else if (isset($_POST['name']))
{
$name=$_POST['name'];
}
else if (isset($_POST['name2']))
{
$name2=$_POST['name2'];
}
& here is my form:
<form action="index.php" method="POST">
<input class="span3 search-query" placeholder="Type User A" type="text" name="name" id="field"/
<input class="span3 search-query" placeholder="Type User B" name="name2" type="text"
id="field2"/>
<button class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
You have to use java script or jQuery for validate both fields are not empty. For Example..
<form action="index.php" method="POST" onsubmit="return validate()">
<input class="span3 search-query" placeholder="Type User A" type="text" name="name" id="field"/>
<input class="span3 search-query" placeholder="Type User B" name="name2" type="text"
id="field2"/>
<button class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
</form>
<script type="text/javascript">
function validate(){
var field1 = document.getElementById('field').value;
var field2 = document.getElementById('field2').value;
if(field1 != '' && field2 != '' ){
return true;
} else{
alert('Type the required fields');
return false;
}
}
</script>
Here if Both fields are not empty then it will be allow to submit form. And In PHP script Add
if(isset($_POST) && !empty($_POST)){
//code comes here
}
I hope it will be helpful for you.
thanks
You can add a check to verify if the request is a post request :
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Place your error checking code here
}
Ehs4n is right, but I would be more specific and do something like :
if(!empty($_POST['compare'])) {
#validation
}
Your button code would have to be changed to :
<button name="compare" value="1" class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
There are two reasons I would do this:
Using !empty() makes sure you don't get an error when $_POST['compare'] is empty
Checking $_POST['compare'] instead of just $_POST makes sure errors are only shown if someone clicks the button.
This last point is key because if you have multiple forms on the page or you happen to set a $_POST variable elsewhere you would still be showing errors.
Use the if condition with isset($_POST) before loading the post.i.e.,
if (isset($_POST)) {
if(empty($name) || empty($name2))
{
echo "Enter a name ";
}
else if (isset($_POST['name']))
{
$name=$_POST['name'];
}
else if (isset($_POST['name2']))
{
$name2=$_POST['name2'];
}
I simply got rid all of all the errors by adding this error_reporting(E_ERROR | E_PARSE); at the start of my code.
However if anyone want to check display validation error messages , one can do easily by what others have mentioned . i.e By using if($_Post).
Anyway ,Thank you everyone for the help.
Add if clause like
if($_POST) {
...your validation code
}
Think of redirecting people AFTER the error to the same page they were:
echo '<script>location.href=\'example.php\'</script>';

PHP error display

I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>

Categories