How to pass php variable FORM data to mail handler? - php

I currently have a form built with HTML/PHP that has some variable data that I'm unable to pass to the mail handler. The inputs with the variable data are blank upon sending mail.
The HTML Form:
<form action="mail-handler.php" method="POST">
<label>First Name:</label>
<input name="T1" type="text" value="<?php print($_GET['firstname']); ?>" disabled="" />
/*Non variable data still needs to pass*/
<label>Phone*:</label>
<input name="phone" type="tel" required="" />
<input type="submit" value="Submit">
</form>
The PHP Mail Handler:
$firstname = $_POST['firstname'];
$phone = $_POST['phone'];
$msgBody="First Name: $firstname\n
Phone: $phone\n";
... and so on.
The form works for every input except the one with the variable data $firstname
How can I get the variable form value for "first name" to pass to the email handler?

So while #Martin and #Adder were correct with the incorrectly assigned var value, even after changing the mail-handler, the data would still not pass through the email.
I found the culprit to actually be the bit of HTML used to keep someone from editing the stored information. I had set the form fields with the variable data to be disabled="". Apparently this was the final block that was preventing the data transfer.
These are the changes I made to the code using the comment advice and changing the disabled status of the input.
<form action="mail-handler.php" method="POST">
<label>First Name:</label>
<input name="nameFirst" type="text" value="<?php print($_GET['firstname']); ?>" readonly="" />
/*Non variable data still needs to pass*/
<label>Phone*:</label>
<input name="phone" type="tel" required="" />
<input type="submit" value="Submit">
</form>
PHP did not like the disabled status so readonly="" got the job done there. Then I changed the var names to better suit my needs:
$nameFirst = $_POST['nameFirst'];
$phone = $_POST['phone'];
$msgBody="First Name: $nameFirst\n
Phone: $phone\n";
This worked very well. Don't use disabled="" on a form in which you want to pass variable data, it won't work. Use readonly="" instead.

Related

Need assistance with PHP and my HTML5 form

I used an anchor tag for my submit button so I think that this is probably why I'm having so much trouble trying to figure this out.
I'm not sure if it's the "href" that is messing it all up. I also would like some assistance with server side validation, not having a lot of experience in PHP, I was only able to validate using JavaScript.
<form id="myform" method="post" name="contact_form" action="process.php">
<input id="cname" type="text" name="name" minlength="2" placeholder="Full Name" class="form-control" required>
<input id="cemail" type="email" name="email" placeholder="Email Address" class="form-control" required>
<textarea id="ccomment" rows="5" name="message" placeholder="Message..." class="form-control" required></textarea>
<div id="send-btn">
SEND
<asp:Button runat="server" Text="submit"/>
</div>
</form>
This below is my PHP code. Please assist with validations and making it work with an anchor tag. I could have messed up the form somewhere.
<?php ob_start();
if (isset($_POST['submit'])) {
$to = "someoneelse#someone.com";
$name = $_POST['name'];
$email = $_POST['email'];
$txt = $_POST['message'];
$headers = "From: .$email" . "\r\n" .
mail($to,$email,$txt,$headers);
header("Location: index.html");
}
?>
Ideally, with modern Javascript you would avoid having any script in your markup and would attach the click event using jquery and prevent the default action for the anchor tag using preventDefault. (See https://api.jquery.com/click/ and https://api.jquery.com/event.preventDefault/ )
However, if you are going to use an onclick attribute, you need to return false. If the onclick event returns false, then the browser will cancel the default action.
SEND
When the anchor link is clicked, the javascript to submit the form will run, but the return false will prevent the link from being followed. The return false will also prevent the browser from jumping to the top when you use a # in your href.
As for server side validation in PHP, you will need to use conditional statements to check that the posted variables match a pattern. See How to validate an email address in PHP .
As said in the comment you just need:
SEND
Small explanation javascript: void(0) or #
If you use javascript: void(0) when you click on the a element the browser will try to run a function called void(0) which should be undefined and do nothing but skip to your onClick.
Instead if you use the # syntax the browser will jump to the top of the page because is looking for some tag with the attribute id empty.
I did as instructed in the anchor tag. The other issue now is nothing happens when I click on submit, is my php code incorrect?
<form id="myform" method="post" name="contact_form" action="process.php">
<input id="cname" type="text" name="name" minlength="2" placeholder="Full Name" class="form-control" required>
<input id="cemail" type="email" name="email" placeholder="Email Address" class="form-control" required>
<textarea id="ccomment" rows="5" name="message" placeholder="Message..." class="form-control" required></textarea>
<div id="send-btn">
SEND
<asp:Button runat="server" Text="submit">
</div>
</form>

Add form ID to JQuery form function

Im in need to create to separate e-mail forms based on AJAX and JQuery.
I need one form to be Standart and other VIP, when getting email from website - i need to indicate from which form customer has send inquiry.
I have sample form for Standard, and need to create VIP form. Imagine it is needed to create forms ID and insert it to JQuery.
Please help
Here is sample form code:
<form id="vip" class="pop_form" action="mail-vip.php">
<h4>ОPlease leave your contacs, we will come back soon!</h4>
<input type="text" name="name" placeholder="Name" required />
<input type="text" name="phone" placeholder="Telephone" required />
<input type="text" name="email" placeholder="E-mail" required />
<input type="text" name="time" placeholder="Callback time" />
<div align="center"><button type="submit">Send</button></div>
</form>
Jquery:
$("form").submit(function() {
$.ajax({
type: "GET",
url: "mail.php",
data: $("form").serialize()
}).done(function() {
alert("Спасибо за заявку!");
setTimeout(function() {
$.fancybox.close();
}, 1000);
});
return false;
});
PHP:
<?php
$recepient = "email;
$sitename = "Website";
$name = trim($_GET["name"]);
$phone = trim($_GET["phone"]);
$email = trim($_GET["email"]);
$email = trim($_GET["time"]);
$pagetitle = "New inquiry for \"$sitename\"";
$message = "Имя: $name \nTelephone: $phone \nE-mail: $email \nTime: $time";
mail($recepient, $pagetitle, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: $recepient");
?>
Thanks!!!
There are various way you can do that.
One of the way could be (minimal change to your code)
Add an hidden field in your form which will be automatically sent to your php and extract it to see it's type.
e.g. <input type="hidden" name="type" value="vip">
So it should look like,
<form id="vip" class="pop_form" action="mail-vip.php">
<h4>ОPlease leave your contacs, we will come back soon!</h4>
<input type="text" name="name" placeholder="Name" required />
<input type="text" name="phone" placeholder="Telephone" required />
<input type="text" name="email" placeholder="E-mail" required />
<input type="text" name="time" placeholder="Callback time" />
<input type="hidden" name="type" value="vip">
<div align="center"><button type="submit">Send</button></div>
</form>
form id is vip i think you need write $("#vip").submit
In the other word,the button where the type "submit " will also submit your form data ,so you don't need write the Ajax
query

Passing a value IF set

I am trying to set up an application form on my site where there is a main large application form on one page (parent.php)and a smaller form on another page (child2.php) that when users fill out some of their details and submit that smaller form, they are taken to the larger form and the details they have entered already appear in the corresponding textbox on the larger form along side some extra boxes for them to fill out(if that makes sense!)
I can get it to work in that the textboxes on the 2nd page display the values of the matching textboxes on the first page, but only when a value is set. As users can either access the main application form through the smaller form OR by directly accessing it, I need to have it so that if the value is set, the set value is displayed and will also be the value entered into the database OR if the value is not pre-set from the smaller form, the user can enter in their info to the main form and this is what's sent to the DB. I think I might need to use ifisset and have tried to do so but am getting nowhere.
Apologies for messy code and the set up of the textboxes as they are just for testing this out and I am still getting to grips with all this and would be grateful if anyone could help me/let me know if I'm on the right track/totally off. Thanks in advance!
Page 1 (parent.php)
<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="Submit">
</div>
</form>
Page 2 (child2.php)
<?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 = $_REQUEST['fName'];} else { echo "first name"; }?>"/>
</br>
<label class="label">surname</label><input class="tb" type="text" id="sName" name="sName" value="<?php if (isset($sName)) { echo $sName = $_REQUEST['sName'];} else { echo "surname"; }?>"/>
</br>
<label class="label">email</label><input class="tb" type="email" id="email" name="email" value="<?php if (isset($email)) { echo $email = $_REQUEST['email'];} else { echo "email"; }?>"/>
</br>
<label class="label">address</label><input class="tb" type="text" id="address" name="address" value="<?php if (isset($address)) { echo $address = $_REQUEST['address'];} else { echo "address"; }?>"/>
</br>
What you're looking for are $_SESSION variables, which stay active until the user closes the browser or until the Session expires (I think the default PHP config time is 24 minutes..?). This is a lot more efficient than storing them in a database for temporal purposes.
So you can set the variables with $_SESSION['fName'] = $_POST['fName']; etc. and then call them later with echo $_SESSION['fName']; etc.
To utilize session variables you will need <?php session_start(); ?> at the beginning of your pages (before any HTML is used)
As suggested by khanahk, using SESSION variables will do your job. The problem with the solution you are thinking is that its fine only as long as you are passing values from one page to some other page, that too after so much mess.
So, you should instead, you should use something like this
session_start();
$email = $_SESSION['email'];
<label class="label">email</label><input class="tb" type="email" id="email" name="email" value="<?php echo $email; ?>"/>

PHP mail keeps giving me undefined index, help?

I have a contact form script, and I added a few fields to it, identical to the rest, but the new variables on submit give 'notices' of undefined index, and the variables do not populate. I grab them POST like this,
$name = $_POST['name'];
$website = $_POST['website'];
$company = $_POST['company'];
$addy = $_POST['addy'];
$email = $_POST['email'];
$phone = $_POST['phone'];
The name, email and phone all work, but website, addy and company do not.
The JavaScript that grabs it looks like so,
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
website: $('#website').val(),
company: $('#company').val(),
addy: $('#addy').val(),
phone: $('#phone').val(),
..etc
What can cause this? I am unsure what other code would be helpful, thank you.
EDIT TO ADD HTML.
Here is some of the form code in the HTML, I can not see anything I missed..
<form method="post" action="send_mail.php" name="contactform" id="contactform">
<fieldset>
<legend>Please fill in the following form to contact us</legend>
<label for=name accesskey=U><span class="required">*</span> Your Name</label>
<input name="name" type="text" id="name" size="30" value="" />
<br />
<label for=email accesskey=E><span class="required">*</span> Email</label>
<input name="email" type="text" id="email" size="30" value="" />
<br />
<label for=website accesskey=W>Website</label>
<input name="website" type="text" id="website" size="30" value="" />
<br />
<label for=company accesskey=C>Company</label>
<input name="company" type="text" id="company" size="30" value="" />
<br />
<label for=addy accesskey=A>Address</label>
<input name="addy" type="text" id="addy" size="30" value="" />
If the values is false or empty, the post won't include those variables in the AJAX call. Recommend you to use isset() in the PHP to verify the variables are set:
$name = isset($_POST['name']) ? $_POST['name'] : '';
etc...
Detailed explanation
If we in javascript (jQuery) has following code:
$.post('url',{
'foo': 'bar',
'baz': $('#nonexisting_element').val(),
'qux': 'quux'
},...);
An #nonexisting_element doesn't exists, it will send following:
foo=bar&qux=quux
and on the PHP side following will end up in the PHP array:
$_POST = array (
'foo' => 'bar'
'qux' => 'quux'
);
jQuery does not send post fields whose value is null. So in your case the error is probably that you don't have fields with the given IDs website, addy, ....
Maybe you forgot to add the id=".." attribute or forgot to change it when copying the old code?

Form validation

I need to create a form that has many of the same fields, that have to be inserted into a database, but the problem I have is that if a user only fills in one or two of the rows, the form will still submit the blank data of the empty fields along with the one or two fields the user has filled in.
How can I check for the rows that have not been filled in and leave them out of the query?
or check for those that have been filled in and add them to the query. . .
The thank_you.php file will capture the $_POST variables and add them to the database.
<form method="post" action="thank_you.php">
Name: <input type="text" size="28" name="name1" />
E-mail: <input type="text" size="28" name="email1" />
<br />
Name: <input type="text" size="28" name="name2" />
E-mail: <input type="text" size="28" name="email2" />
<br />
Name: <input type="text" size="28" name="name3" />
E-mail: <input type="text" size="28" name="email3" />
<br />
Name: <input type="text" size="28" name="name4" />
E-mail: <input type="text" size="28" name="email4" />
<input type="image" src="images/btn_s.jpg" />
</form>
I am assuming that I could use javascript or jQuery to accomplish this, how would I go about doing this?
Thanx in advance for the help.
As others have said, it's bad practise to rely on javascript as your only form of validation. Look to javascript as a way to help your users submit valid data - but you should always validate on the server side. With that in mind, here's my suggestion:
<form method="post" action="thank_you.php">
Name: <input type="text" size="28" name="name1" />
E-mail: <input type="text" size="28" name="email1" />
<br />
Name: <input type="text" size="28" name="name2" />
E-mail: <input type="text" size="28" name="email2" />
<br />
Name: <input type="text" size="28" name="name3" />
E-mail: <input type="text" size="28" name="email3" />
<br />
Name: <input type="text" size="28" name="name4" />
E-mail: <input type="text" size="28" name="email4" />
<input type="image" src="images/btn_s.jpg" />
</form>
<?php
$num = 4; //Number of times the field is repeated
for($i = 1; $i <= $num; $i++){
if($_POST['name'.$i] != '' && $_POST['email'.$i] !=''){ //Only process if name and email are not blank
$thisname = $_POST['name'.$i];
$thisemail = $_POST['email'.$i];
//Your code here
}
}
?>
It's good to use javascript for form validation, but you shouldn't rely on it. The first thing to do is to check the values in $_POST in PHP, and make sure they're something valid looking (or at the very least, check that they're not "").
To check with javascript, you would put an onSubmit="..." in the form tag, which returns false if the form data is invalid (meaning "don't submit the form"). And you'd also probably want an alert, or you could modify the page somehow to indicate the problem. I'm not going to write out a form validation script for you though.
You can do JavaScript validation by using the submit button to call a JavaScript function instead of submitting the form. If the data passes your validation criteria, the JavaScript function can then submit the data. However, you should not rely completely on JavaScript validation. If the user has JavaScript disabled, their data will not be validated, so your PHP application must be robust enough to handle blank data. It isn't just blank data that you need to be concerned with, though. You need to validate the user input for garbage and sanitize the data before using it in the database.
I don't know the exact PHP syntax, but I'll write some pseudo-code that ought to do the trick. The basic idea is when you retrieve the $_POST values, you'll want to create a new hash that has values that are acceptable and then you can pass that hash to whatever methods needs to build out queries or whatever. The way I'll do this is to remove invalid values from the hash entirely, so it appears they were never there. Obviously, you can do this differently (mark them as invalid, etc).
$cleaned_args = array();
foreach ($_POST as $key => $value) {
if ($_POST[$key] != "" && is_valid_email($_POST[$key])) {
$cleaned_args[$key] = $_POST[$key];
}
make_db_call_or_whatever($cleaned_args);
where is_valid_email is a method that maybe PHP has or you have to write. You could even generalize the if clause into an is_valid($_POST[arg]) method if you want, but it depends on how complex the situation is.
Hopefully, this helps to give you an idea of how to do this. I think this will be easier than dynamically removing inputs with JavaScript before the form submission and, as mentioned, will be more secure than doing it only on the client side.

Categories