I have a simple form, inside it there is check-boxes and multi selection inputs.
The problem I am having is:
The multi selection input only submits the last selection!
The checkboxes only works if I set a value="" but shouldn't work without it?
Here is the form:
<fieldset>
<p>Multi selection</p>
<select name="dropdown2[]" class="select multi-select " data-placeholder="Choose an option" multiple="multiple">
<optgroup label="Section">
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
</optgroup>
<optgroup label="Section">
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
</optgroup>
</select>
</fieldset>
<fieldset>
<p>Optional checkboxs</p>
<label class="checkbox">
<input name="11" type="checkbox"><span><i></i></span>
<p>CheckA</p>
</label>
<label class="checkbox">
<input name="11" type="checkbox"><span><i></i></span>
<p>CheckB</p>
</label>
</fieldset>
Here is the PHP:
<?php
// Only start sessions if they haven't been already to prevent errors
if (empty($_SESSION)){session_start();}
// If 'data' var was received via POST from form-validation.js
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// There's not really a need for this line with modern browsers
ob_start();
// Open the div around the message
$message = "<div style=\"styling stuff\">";
// Loop through every single post value
foreach ($_REQUEST as $key => $value) {
// If it's not empty
if (!empty($value)) {
// Change the name attributes to look a bit more human-readable
$thisKey = str_replace("-", " ", str_replace("_", "|", $key));
// Populate the message var
$message .= "<strong>" . $thisKey . ":</strong> " . $value . "<br />";
}
}
// Close the div around the message
$message .= '</div>';
// Mail variables
$to = 'email#email.com';
$subject = 'New Message';
$headers = "From: email#email.com\r\n";
$headers .= "Reply-To: email#email.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Attempt to send
$sendMail = #mail($to, $subject, $message, $headers);
// If it fails...
if (!$sendMail) {
// Terminate processing with error
die("There was a problem sending the email");
} else {
// Terminate processing with success msg
die("Email was sent!");
}
// As above, no real need for this line with modern browsers
ob_flush();
// Terminate
die();
}
?>
Live preview: http://loaistudio.com/contact
If you want to send multiple values via checkboxes, then they should be used in this way
<input name="11[]" type="checkbox">
<input name="11[]" type="checkbox">
instead of
<input name="11" type="checkbox">
if you need to submit multi check box then
use like this
<input name="11[]" type="checkbox" value="someval">
<input name="11[]" type="checkbox" value="someval" >
this will post checkbox elements as array
to retrieve
$chk = $_POST['11']; // this will be array
iterate through this array you will get all checked elements of name 11
still you need to provide some values to check box to work this
Related
I am new to this and trying to figure out how to add a few extra features to this code.
On submit the page needs to redirect to an external URL i.e. www.google.com
The checkbox must be automatically checked and when the client gets emailed the details it must return TRUE/FALSE for subscriptions to the newsletter (so client knows whether they want to opt in or not)
This is my PHP code:
<?php
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'nissberry#gmail.com';
$subscriber_email = addslashes(trim($_POST['email']));
if (!isEmail($subscriber_email)) {
$array = array('valid' => 0, 'message' => 'Insert a valid email address!');
echo json_encode($array);
} else {
$array = array('valid' => 1, 'message' => 'Thanks for your subscription!');
echo json_encode($array);
// Send email
$subject = 'New Subscriber (Free eBook)!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
// $headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body);
}
?>
And this is my HTML:
<form class="form-inline" role="form" action="assets/subscribe.php" method="post">
<div class="form-group">
<label class="sr-only" for="subscribe-email">Email address</label>
<input type="text" name="email" placeholder="Enter your email..." class="subscribe-email form-control" id="subscribe-email">
</div>
<button type="submit" class="btn">Receive your free eBook</button>
<br>
<div class="checkbox">
<label>
<input type="checkbox" class="checked"> Receive Our Monthly Newsletter
</label>
</div>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
If there was no output before mail() function (no echo or html) you
could use this just before closing PHP tag:
header("Location: www.google.com");
exit;
So to redirect with PHP you need to remove all echo's from your code. If this can't be done, use javascript:
window.location.replace("www.google.com");
Add 'checked' attribute to your checkbox. It should have a name too,
so you can access it with global $_POST variable:
<input name="newsletter" type="checkbox" class="checked" checked>
Then you can extend your message:
$newsletter_subscription = isset($_POST['newsletter']) ? 'TRUE' : 'FALSE';
$body .= 'Newsletter subscription: '.$newsletter_subscription;
I have somewhat of an "order" page set up that allows people to select items for purchase. When they hit "order" it takes them to a page that allows them to select details for each item drom dynamically populated drop downs. These drop downs are in a loop so that each item has its own set.
This is where my issue starts. If there is only one item on the order page it works perfectly. All the selected info from the drop downs is pulled into my PHP script, and it formats it into an email and sends the order to me. If there is more than 1 item in the order, it will only send the last item on the page.
Here is the code for the dropdowns...
<form name="mediumselect">
<table>
<tr>
<td>
<select name="sel" onchange="selFormat(this);" style="width:200px">
<option value="">-Please select delivery format-</option>
<option value="File">File</option>
<option value="Tape">Tape</option>
<option value="Disc">Disc</option>
</select>
</td>
<td>
<select name="formats" onchange="selRate(this)" style="width:150px">
</select>
</td>
<td>
<select name="framerate" onchange="selColor(this)" style="width:150px">
</select>
</td>
<td>
<select name="color" style="width:150px">
</select>
</td>
</table>
</form>
Here is the PHP...
<?php
$asset = $_REQUEST['assetname'];
$medium = $_REQUEST['sel'];
$type = $_REQUEST['formats'] ;
$framerate = $_REQUEST['framerate'] ;
$color = $_REQUEST['color'] ;
$body = <<<EOD
Asset Name: $asset
Asset format: $medium
Format Type: $type
Frame Rate/Resolution: $framerate
Codec or Color Subsample: $color
EOD;
$results = <<<EOD
<html>
<head>
<title>sent message</title>
<style type="text/css">
</style>
</head>
<div align="center">One your order is submitted, a confirmation email will be sent to above email with order details.</div>
</div>
</body>
</html>
EOD;
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{
//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
} else {
//send email
global $body;
global $results;
$email = $_REQUEST['email'] ;
mail("~~~#gmail.com", "Subject: INCOMING ORDER", $body, "From: $email" );
echo "$results";
}
} else {//if "email" is not filled out, display the form
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text'><br>
Subject: <input name='subject' type='text'><br>
Message:<br>
<textarea name='message' rows='15' cols='40'>
</textarea><br>
<input type='submit'>
</form>";
}
?>
I am still new to PHP and if there is a better way to go about doing this I would be grateful for the advice.
I would recommend putting all the $body values into a single string. So first loop through every item and just add to the string $body using PHP concatenation ($body . =). Currently you are only retrieving one value. Perhaps change the names of your fields by looping through them for how many items there are ++ a number following the name in order to loop through those _REQUESTS for that those fields in put them into you $body .= string for email.
I have set up a contact form, and set it to email the response to an email account. Part of the form is a series of checkboxes, and I need to get these to display in the email as a list. This is the code I have below, which at the moment returns 'Array' instead of the values of the checkboxes. Any suggestions?
HTML:
<h3>Service required:</h3>
<input type="text" id="name" name="name" placeholder="Name" required />
<input type="email" id="email" name="email" placeholder="Email" required />
<input class="check-box styled" type="checkbox" name="service[]" value="Service / repairs" /><label> Service / repairs</label>
<input class="check-box styled" type="checkbox" name="service[]" value="MOT" /><label> MOT</label>
<input class="check-box styled" type="checkbox" name="service[]" value="Cars for sale" /><label> Cars for sale</label>
Here's the php:
<?php
if (isset($_POST['service'])) {
$service = $_POST['service'];
// $service is an array of selected values
}
$formcontent= "From: $name \n Service(s) required: $service \n";
$recipient = "name#email.com";
$subject = "You have a new message from $name";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You! We will get back to you as soon as we can.";
?>
Thanks,
Jason
You should join (for example implode with ', ') your array elements to a string.
<?php
$formcontent= "From: $name \n Service(s) required: ".implode(", " ,$service)." \n";
?>
Why don't you loop through the array to get the desired results into a String?
if (isset($_POST['service'])) {
$service = $_POST['service'];
// $service is an array of selected values
$service_string = "";
for($i=0;$i<count($service);$i++)
{
if($i!=0)
{
$service_string = $service_string . ", ";
}
$service_string = $service_string . $service[$i];
}
}
You will then get an output of a comma separated list of each ticked item as $service_string.
Since several checkboxes are stored in $_POST['service'], it is an array itself and has become two-dimensional. Its different indexes are accessible like this: $_POST['service'][0].
To do something with $_POST['service'], you can use foreach to loop through all indexes:
foreach($_POST['service'] as $post){
//Do stuff here
}
Alternatively, use implode() to simply concatenate all indexes.
Your input type checkbix must have unique names. Otherwise last checkbox will be found in $_POST. Or you can loop through as discuss above. Make your email html format and write a string of html to $formcontent. e.g.
$formcontent = "<html><head></head><body>";
$formcontent .= "<ul><li>".$_POST["checkbox1"]."</li>";
$formcontent .= "<li>".$_POST["checkbox2"]."</li>";
$formcontent .= "</ul></body></html>";
To write email in html format see mail function on php website.
Im trying to write a contact form and so far everything works only theres a multiple checkbox in the form and im unsure how to call all data and so my email returns 'array' for the variable 'service'
My code is...
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$service = $_POST['service'];
$description = $_POST['description'];
$location = $_POST['location'];
$to = "liam#.co.uk";
//begin of HTML message
$message = "
From : $name,
Email: $email,
Number: $number,
Service: $service,
Description: $description
Location: $location
";
//end of message
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=iso-8859-1rn";
$headers .= "From: $email\r\n";
mail($to, $subject, $message, $headers);
?>
My form for the service input is...
<dt><input type="checkbox" value="Static guarding" name="service[]" class="cbox">Static guarding</dt>
<dt><input type="checkbox" value="Mobile Patrols" name="service[]"class="cbox">Mobile Patrols</dt>
<dt><input type="checkbox" value="Alarm response escorting" name="service[]"class="cbox">Alarm response escorting</dt>
<dt><input type="checkbox" value="Alarm response/ Keyholding" name="service[]"class="cbox">Alarm response/ Keyholding</dt>
<dt><input type="checkbox" value="Other" name="service[]"class="cbox">Other</dt>
<dt><input type="hidden" value="Other" name="service[]"class="cbox"></dt>
You can process the checkbox values into a string with implode():
$checkboxes = implode(',', $_POST['service']);
$message = <<<EOL
...
Service: $checkboxes
EOL;
Note the use of a heredoc - it's a MUCH nicer way of defining a multi-line string than using a regular quoted string.
Because you appended your form input names with brackets, PHP will form an indexed array out of them.
$sCount = count($service);
for ($s=0; $s<$sCount; $s++) {
echo $service[$s];
}
You might be better off creating an associative array:
<dt><input type="checkbox" value="Mobile Patrols" name="service[mobile]"class="cbox">Mobile Patrols</dt>
<dt><input type="checkbox" value="Alarm response escorting" name="service[escorting]"class="cbox">Alarm response escorting</dt>
That way, in your script, you could access them as:
echo $service['mobile'];
echo $service['escorting'];
Note that empty checkboxes aren't submitted so you'll want to first check if the array element is set.
I have a "tell a friend" pop up email form that allows users to share my page with an email address that they enter. It pops up fine, but I can't get the form to send the email.
html:
<div id="tellfriend">
Close
<form id='tellafriend_form' method="post" action="#sendMessage" name="tellafriend_form">
<label for="name">Your Name:</label>
<input type="text" id="name" name="name" />
<label for="to">Friend's email:</label>
<input type="text" id="to" name="to" />
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject" />
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div><!-- #tellfriend -->
javascript that handles the "pop up":
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script>
$(function() {
$('#tellfriend').hide();
$('#sendMessage').click(function(e) {
$("#tellfriend").fadeToggle('fast');
});
});
</script>
php that's supposed to send the mail:
<?
if (isset($_POST['Submit'])) {
// This will check to see if the form has been submitted
$senders_name = $_POST['name'];
// The person who is submitting the form
$recipient_friend = $_POST['to'];
// The forms recipient
$subject = $_POST['subject'];
// The subject line
$message = $_POST['message'];
// The message being sent
mail($recipient_friend, "From $senders_name", $subject, $message);
if (isset($_POST['your_email'])) {
echo "<br>Your friend has been contacted <br><br>Thank you $senders_name";
}}
?>
Disclaimer: PHP newbie, hoping to learn. Thanks!
The order of your parameters in mail function is not correct. see this
it should be
mail($recipient_friend, $subject, $message);
if you want to use headers then do this
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: '.$recipient_friend.' <'.$recipient_friend.'>' . "\r\n";
$headers .= 'From: '.$sender.' <'.$senderEM.'>' . "\r\n";
Then call mail like this
mail($recipient_friend, $subject, $message, $headers);
You have one error in your PHP code:
if (isset($_POST['Submit'])) {
should be:
if (isset($_POST['submit'])) {
with a lowercase "s".
Indeed the name of you submit button is "submit" but the value is "Submit".
You could eventually do that:
if (isset($_POST['submit']) && $_POST['submit'] == 'Submit') {
And your mail parameters are not correct like boug said.
You have 2 errors
first:
if (isset($_POST['submit']))
// $_POST is case sensitive
second:
if (isset($_POST['your_email']))
// you dont have an inout named 'your_email'