This started off as a pre-built contact form that came bundled in an HTML template. All of the textbox field work perfectly fine when submitting the from. However I need some help with a checkbox section I added myself. I've been trying to do some research but can't get the script to include all the selected checkboxes in the e-mail.
Here's my working html:
<form class="nobottommargin" id="template-contactform" name="template-contactform" action="include/sendemail.php" method="post">
<div class="form-process"></div>
<div class="col_half">
<label for="template-contactform-name">Name <small>*</small></label>
<input type="text" id="template-contactform-name" name="template-contactform-name" value="" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="template-contactform-email">Email <small>*</small></label>
<input type="email" id="template-contactform-email" name="template-contactform-email" value="" class="required email sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_half">
<label for="template-contactform-phone">Phone <small>*</small></label>
<input type="text" id="template-contactform-phone" name="template-contactform-phone" value="" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="template-contactform-budget">Budget</label>
<input type="text" id="template-contactform-budget" name="template-contactform-budget" value="" class="sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_full">
<label for="template-contactform-services[]">Services Required: </label>
<input name="template-contactform-services[]" type="checkbox" value="Web-Design" />Web Design
<input name="template-contactform-services[]" type="checkbox" value="E-Commerce" />E-Commerce
<input name="template-contactform-services[]" type="checkbox" value="User-Experience" />User Experience
<input name="template-contactform-services[]" type="checkbox" value="Branding" />Branding
<input name="template-contactform-services[]" type="checkbox" value="Mobile-Design" />Mobile Design
<input name="template-contactform-services[]" type="checkbox" value="Search-Marketing" />Search Marketing
</div>
<div class="col_full">
<label for="template-contactform-message">Deliverables & Goals <small>*</small></label>
<textarea class="required sm-form-control" id="template-contactform-message" name="template-contactform-message" rows="4" cols="30" placeholder="List the specific deliverables, services, and goals required..."></textarea>
</div>
<div class="col_full">
<label for="template-contactform-missing">Anything Missing?</label>
<textarea class="sm-form-control" id="template-contactform-missing" name="template-contactform-missing" rows="4" cols="30" placeholder="Is there anything else you think we should know?"></textarea>
</div>
<div class="col_full hidden">
<input type="text" id="template-contactform-botcheck" name="template-contactform-botcheck" value="" class="sm-form-control" />
</div>
<div class="col_full">
<!--<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-sitekey="your-recaptcha-site-key"></div>-->
</div>
<div class="col_full">
<button class="button button-3d nomargin" type="submit" id="template-contactform-submit" name="template-contactform-submit" value="submit">Send Message</button>
</div>
</form>
and here's my php:
<?php
require_once('phpmailer/PHPMailerAutoload.php');
$toemails = array();
$toemails[] = array(
'email' => 'info#mydomain.com', // Your Email Address
'name' => 'Your Name' // Your Name
);
// Form Processing Messages
$message_success = 'We have <strong>successfully</strong> received your Message and will get Back to you as soon as possible.';
// Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = 'your-recaptcha-secret-key'; // Your reCaptcha Secret
$mail = new PHPMailer();
// If you intend you use SMTP, add your SMTP Code after this Line
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( $_POST['template-contactform-email'] != '' ) {
$name = isset( $_POST['template-contactform-name'] ) ? $_POST['template-contactform-name'] : '';
$email = isset( $_POST['template-contactform-email'] ) ? $_POST['template-contactform-email'] : '';
$phone = isset( $_POST['template-contactform-phone'] ) ? $_POST['template-contactform-phone'] : '';
$budget = isset( $_POST['template-contactform-budget'] ) ? $_POST['template-contactform-budget'] : '';
$service = isset( $_POST['template-contactform-services'] ) ? $_POST['template-contactform-services'] : '';
$message = isset( $_POST['template-contactform-message'] ) ? $_POST['template-contactform-message'] : '';
$missing = isset( $_POST['template-contactform-missing'] ) ? $_POST['template-contactform-missing'] : '';
$subject = isset($subject) ? $subject : 'New Message From Contact Form';
$botcheck = $_POST['template-contactform-botcheck'];
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
foreach( $toemails as $toemail ) {
$mail->AddAddress( $toemail['email'] , $toemail['name'] );
}
$mail->Subject = $subject;
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$phone = isset($phone) ? "Phone: $phone<br><br>" : '';
$budget = isset($budget) ? "Budget: $budget<br><br>" : '';
$service = isset($service) ? "Services Required: $service<br><br>" : '';
$message = isset($message) ? "Deliverables & Goals: $message<br><br>" : '';
$missing = isset($missing) ? "Anything Missing: $missing<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = "$name $email $phone $budget $service $message $missing $referrer";
// Runs only when File Field is present in the Contact Form
if ( isset( $_FILES['template-contactform-file'] ) && $_FILES['template-contactform-file']['error'] == UPLOAD_ERR_OK ) {
$mail->IsHTML(true);
$mail->AddAttachment( $_FILES['template-contactform-file']['tmp_name'], $_FILES['template-contactform-file']['name'] );
}
// Runs only when reCaptcha is present in the Contact Form
if( isset( $_POST['g-recaptcha-response'] ) ) {
$recaptcha_response = $_POST['g-recaptcha-response'];
$response = file_get_contents( "https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptcha_secret . "&response=" . $recaptcha_response );
$g_response = json_decode( $response );
if ( $g_response->success !== true ) {
echo '{ "alert": "error", "message": "Captcha not Validated! Please Try Again." }';
die;
}
}
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
echo '{ "alert": "success", "message": "' . $message_success . '" }';
else:
echo '{ "alert": "error", "message": "Email <strong>could not</strong> be sent due to some Unexpected Error. Please Try Again later.<br /><br /><strong>Reason:</strong><br />' . $mail->ErrorInfo . '" }';
endif;
} else {
echo '{ "alert": "error", "message": "Bot <strong>Detected</strong>.! Clean yourself Botster.!" }';
}
} else {
echo '{ "alert": "error", "message": "Please <strong>Fill up</strong> all the Fields and Try Again." }';
}
} else {
echo '{ "alert": "error", "message": "An <strong>unexpected error</strong> occured. Please Try Again later." }';
}
?>
Thanks in advance
You have to give different name attributes to the <input type="checkbox" /> tag. Then you can check whether a checkbox is checked with the isset() function.
Related
I created registration form and corresponding controller and backend php code.
The registered data is storing correctly . But i am not reciving mail in my email id. Please help me with this..
My html Code
<div class="col-lg-6 col-lg-offset-3 well " style="margin-top:1em; background-color:black; ">
<h4 style="color:white; text-align:center;"> <strong> FILL UP REGISTRAION FORM </strong> </h4>
</div>
<div class="col-lg-6 col-lg-offset-3 well" style="margin-bottom:10em;">
<form name="register" ng-app="TempleWebApp" ng-controller="RegisterCtrl" ng-submit="SignUp(register.$valid)" novalidate>
<!-- First Name -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.fname.$invalid && (register.fname.$dirty || submitted)}">
<label>First Name</label>
<input class="form-control" type="text" name="fname" ng-model="fname" placeholder="First Name" ng-required="true">
<span class="help-block" ng-show="register.fname.$invalid && register.fname.$error.required && (register.fname.$dirty || submitted)">
First Name is required.</span>
</div>
<!-- Last Name -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.lname.$invalid && (register.lname.$dirty || submitted)}">
<label>Last Name</label>
<input class="form-control" type="text" name="lname" ng-model="lname" placeholder="Last Name" ng-required="true">
<span class="help-block" ng-show="register.lname.$invalid && register.lname.$error.required && (register.lname.$dirty || submitted)">
Last Name is required.</span>
</div>
<!-- City -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.city.$invalid && (register.city.$dirty || submitted)}">
<label>City</label>
<input class="form-control" type="text" name="city" ng-model="city" placeholder="City" ng-required="true">
<span class="help-block" ng-show="register.city.$invalid && register.city.$error.required && (register.city.$dirty || submitted)">
City is required.</span>
</div>
<!-- Gender -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.gender.$invalid && (register.gender.$dirty || submitted)}">
<label>Gender</label> <br>
<input type="radio" name="gender" ng-model="gender" value="male" ng-required="true"> Male
<input type="radio" name="gender" ng-model="gender" value="female" ng-required="true" style="margin-left:5em;"> Female
<span class="help-block" ng-show="register.gender.$invalid && register.gender.$error.required && (register.gender.$dirty || submitted)">
Gender is required.</span>
</div>
<!-- Email -->
<div class="form-group col-lg-12" ng-class="{ 'has-error' : register.email.$invalid && (register.email.$dirty || submitted)}">
<label>Email</label>
<input class="form-control" type="text" name="email" ng-model="useremail" placeholder="Email" ng-pattern="/^[^\s#]+#[^\s#]+\.[^\s#]{2,}$/" ng-required="true">
<span class="help-block" ng-show="register.email.$invalid && register.email.$error.required && (register.email.$dirty || submitted)">
Email is required.</span>
<span class="help-block" ng-show="register.email.$error.pattern">
Enter Valid Email .</span>
</div>
<!-- Password -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.password.$invalid && (register.password.$dirty || submitted)}">
<label>Password</label>
<input class="form-control" type="password" name="password" ng-model="userpassword" placeholder="Password" ng-required="true">
<span class="help-block" ng-show="register.password.$invalid && register.password.$error.required && (register.password.$dirty || submitted)">
Password is required.</span>
</div>
<!-- CONFIRM PASSWORD -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.confirmPassword.$invalid && (register.confirmPassword.$dirty || submitted)}">
<label>Confirm Password</label>
<input type="Password" name="confirmPassword" class="form-control" ng-model="confirmPassword" placeholder="Confirm Your Password" ng-compare="password" ng-required="true">
<p ng-show="register.confirmPassword.$error.required && (register.confirmPassword.$dirty || submitted)" class="help-block">confirm password is required.</p>
<p ng-show="register.confirmPassword.$error.compare && (register.confirmPassword.$dirty || submitted)" class="help-block">Confirm password doesnot match.</p>
</div>
<div class="col-lg-12 well " ng-repeat="error in errors" style="background-color:red; margin-top:0.5em;"> {{ error}} </div>
<div class="col-lg-12 well" ng-repeat="msg in msgs" style="margin-top:0.5em;">
<h5 style="color:green;">{{ msg}} </h5>
</div>
<button type="submit" class="btn btn-success col-lg-12">
<span ng-show="searchButtonText == 'REGISTERING'"><i class="glyphicon glyphicon-refresh spinning"></i></span>
{{ searchButtonText }}
</button>
</form>
</div>
My controller
app.controller('RegisterCtrl', function ($scope,$location, $http,$timeout) {
$scope.gender = '';
$scope.errors = [];
$scope.msgs = [];
$scope.searchButtonText = "REGISTER DETAILS";
$scope.test = "false";
$scope.SignUp = function(isValid) {
// Set the 'submitted' flag to true
$scope.submitted = true;
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
if (isValid) {
$http.post('php/register.php',
{ 'fname': $scope.fname,
'lname': $scope.lname,
'city': $scope.city,
'gender': $scope.gender,
'pswd' : $scope.userpassword,
'email': $scope.useremail
})
.success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
$scope.test = "true";
$scope.searchButtonText = "REGISTERING";
//var goTopayment = function() { $scope.searchButtonText = "REGISTER DETAILS"; $location.path('/login'); };
// $timeout(goTopayment, 3000);
}
else
{
$scope.errors.push(data.error);
}
})
.error(function(data, status) { // called asynchronously if an error occurs or server returns response with an error status.
$scope.errors.push(status);
});
} // closing bracket for IF(isvalid)
} // closing bracket for $scope.SIGNUP = function
}); // closing bracket for register
My php Code is
<?php
$data = json_decode(file_get_contents("php://input"));
$fname = mysql_real_escape_string($data->fname);
$lname = mysql_real_escape_string($data->lname);
$city = mysql_real_escape_string($data->city);
$gender = mysql_real_escape_string($data->gender);
$upswd = mysql_real_escape_string($data->pswd);
$uemail = mysql_real_escape_string($data->email);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('registraion', $con);
$qry_em = 'select count(*) as cnt from users where Email ="' . $uemail . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (Firstname,Lastname,City,Gender,Password,Email) values
("' . $fname . '","' . $lname . '","' . $city . '","' . $gender . '","' . $upswd . '","' . $uemail . '")';
$qry_res1 = mysql_query($qry);
if (!$qry_res1) {
die('Invalid query: ' . mysql_error());
} else {
return mysql_insert_id();
}
$current_id = mysql_insert_id(); //last insert id
if(!empty($current_id)) {
$actual_link = "http://localhost/angular/php/"."activate.php?uid=" . $current_id;
$EmailTo = $uemail ;
$Subject = "User Registration Activation Email";
$Content = "Click this link to activate your account. <a href='" . $actual_link . "'>" . $actual_link . "</a>";
$MailHeaders = "From: Admin\r\n";
$success = mail($EmailTo, $Subject, $Content, $MailHeaders);
if($success ) {
$arr = array('msg' => "You have registered and the activation mail is sent to your email. Click the activation link to activate you account.", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
}
}
}
else
{
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
?>
Finally I solved it. The problem was finding last inserted id value for $current_id variable.Since i was not getting correct value for this variable, value for $Emailto variable is not assigned with email id. So I changed php code to following way.
<?php
$data = json_decode(file_get_contents("php://input"));
$fname = mysql_real_escape_string($data->fname);
$lname = mysql_real_escape_string($data->lname);
$city = mysql_real_escape_string($data->city);
$gender = mysql_real_escape_string($data->gender);
$upswd = mysql_real_escape_string($data->pswd);
$uemail = mysql_real_escape_string($data->email);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('registraion', $con);
$qry_em = 'select count(*) as cnt from users where Email ="' . $uemail . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (Firstname,Lastname,City,Gender,Password,Email) values
("' . $fname . '","' . $lname . '","' . $city . '","' . $gender . '","' . $upswd . '","' . $uemail . '")';
$qry_res1 = mysql_query($qry);
//changed current_id value finding method.
$current_id = mysql_query("select uid from users ORDER BY uid DESC LIMIT 1"); //last insert id
if(!empty($current_id)) {
$actual_link = "http://localhost/angular/php/"."activate.php?uid=" . $current_id;
$EmailTo = $uemail;
$Subject = "User Registration Activation Email";
$Content = "Click this link to activate your account. <a href='" . $actual_link . "'>" . $actual_link . "</a>";
$MailHeaders = "From: Admin\r\n";
if(mail($EmailTo, $Subject, $Content, $MailHeaders) ) {
$arr = array('msg' => "You have registered and the activation mail is sent to your email. Click the activation link to activate you account.", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
}
}
}
else
{
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
?>
What I am trying to do is before I submit a form to Mailchimp with someones email I want to write that email to a .txt file. Mailchimp is using a "get" for the form and the "action" is run on mailchimp not the same page as form. Here is my code for the form.
<form id="subscribe-form1" action="https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff"
method="get" class="form-inline">
<div class="input-group">
<input type="email" class="form-control" placeholder="Email address" name="EMAIL">
<div class="input-group-btn">
<button class="btn btn-grn" type="submit button" data-toggle="modal" data-target="#myModal">Sign Up</button>
</div>
</div>
<div style="visibility:collapse;" id="subscribe-result1"> </div>
<div class="checkbox">
<label>
<input type="checkbox" id="mce-group[6917]-6917-0" name="group[6917][1024]" value="1024" checked="checked" style="">
I agree to recieve FREE newsletter from Personal Trainer Food </label>
</div>
<?php //this only works if I change get->post and action ="" but then it does not submit to mail chimp.
//Get the email from POST
$email = $_REQUEST['EMAIL'];
$file = fopen("document.txt","a+");
fwrite($file,$email . "\n");
//redirect
?>
</form>
You can try appending the values manually to the URL, then redirecting to it:
▼
<form id="subscribe-form1" action="" method="get" class="form-inline">
<div class="input-group">
<input type="email" class="form-control" placeholder="Email address" name="EMAIL">
<div class="input-group-btn">
<button class="btn btn-grn" type="submit button" data-toggle="modal" data-target="#myModal">Sign Up</button>
</div>
</div>
<div style="visibility:collapse;" id="subscribe-result1"> </div>
<div class="checkbox">
<label>
<input type="checkbox" id="mce-group[6917]-6917-0" name="group[6917][1024]" value="1024" checked="checked" style="">
I agree to recieve FREE newsletter from Personal Trainer Food </label>
</div>
<?php //this only works if I change get->post and action ="" but then it does not submit to mail chimp.
//Get the email from GET ◄■■■
$email = $_REQUEST['EMAIL'];
$file = fopen("document.txt","a+");
fwrite($file,$email . "\n"); URL PARAMETERS START
fclose($file); // ◄■■■ ▼
header("Location: https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email"); // ◄■■■
exit; // ◄■■■
?>
</form>
Notice the original "chimp" URL contains an ampersand $amp; as HTML symbol. I think we can get rid of it and use the "natural" ampersand &.
There is a checkbox in your form, we can add it too:
fclose($file); // ◄■■■
if ( isset( $_GET["group[6917][1024]"] ) ) // IF CHECKBOX IS CHECKED...
$chk = "&group[6917][1024]=1024"; URL PARAMETERS START
else $chk = ""; ▼
header("Location: https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk"); // ◄■■■
exit; // ◄■■■
The variables $email and $chk are at the end of the URL. An example of the resulting URL would be:
https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=josmanaba#yahoo.com&group[6917][1024]=1024
Edit :
Added an if to the PHP code:
<?php
if ( isset( $_GET["EMAIL"] ) ) {
$email = $_REQUEST['EMAIL'];
if ( isset( $_GET["group"] ) )
$chk = "&group[6917][1024]=1024";
else $chk = "";
header("Location: https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk");
exit;
}
?>
Edit #2 :
<?php
if ( isset( $_GET["EMAIL"] ) ) {
$email = $_REQUEST['EMAIL'];
// SAVE EMAIL.
$file = fopen("document.txt","a");
fwrite($file,$email . "\n");
fclose($file);
if ( isset( $_GET["group"] ) )
$chk = "&group[6917][1024]=1024";
else $chk = "";
header("Location: https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk");
exit;
}
?>
Edit #3
Redirect with a form and auto-submit it with javascript:
<?php
if ( isset( $_GET["EMAIL"] ) ) {
$email = $_REQUEST['EMAIL'];
// SAVE EMAIL.
$file = fopen("document.txt","a");
fwrite($file,$email . "\n");
fclose($file);
if ( isset( $_GET["group"] ) )
$chk = "&group[6917][1024]=1024";
else $chk = "";
echo "<form method='get'" .
" id='frm'" .
" target='_blank'" .
" action='https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk'>" .
"</form>" .
"<script type='text/javascript'>" .
"document.getElementById('frm').submit();" .
"</script>";
exit;
}
?>
Edit #4 :
This is edit #2 but saving the URL in the textfile :
<?php
if ( isset( $_GET["EMAIL"] ) ) {
$email = $_REQUEST['EMAIL'];
if ( isset( $_GET["group"] ) )
$chk = "&group[6917][1024]=1024";
else $chk = "";
$url = "https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk"
// SAVE EMAIL.
$file = fopen("document.txt","a");
fwrite($file,$email . "\n");
fwrite($file,$url . "\n");
fclose($file);
header("Location: $url");
exit;
}
?>
I'm probably missing something really simple here or have a little typo in my code but the PHP form I've created for a WordPress site I'm building won't send. If there are errors in the form, the validation works (except for if you just enter a name) but when you fill in the form correctly and click submit, it simply goes to the page it's meant to for processing and says 'Sorry, no posts matched your criteria.'. Plus the mail doesn't get sent.
EDIT
The link to the dev site is http://dev.garethdaine.com/inkframe/.
The page for processing does exist. Here's my code:
Form Code
<form name="quick-contact" class="quick-contact" method="post" action="<?php bloginfo('url'); ?>/get-in-touch/">
<h3>Request a Call Back</h3>
<h4><label for="name">Name</label></h4>
<input id="name" name="name" type="text" />
<h4><label for="email">Email</label></h4>
<input id="email" name="email" type="text" />
<h4><label for="phone">Phone</label></h4>
<input id="phone" name="phone" type="text" />
<input id="submit" type="submit" value="Submit" />
<input type="hidden" name="submitted" id="submitted" value="true" />
<input type="hidden" name="required" id="required" class="required" />
</form>
PHP Code
<?php
/*
* Template Name: Contact
*/
if( isset( $_POST['submitted'] ) ) {
$to = get_option( 'admin_email' );
if( trim( $_POST['name'] ) === '' ) {
$nameError = 'You did not enter your name.';
$hasError = true;
} else {
$name = trim( $_POST['name'] );
}
if( trim( $_POST['email'] ) === '' ) {
$emailError = 'You did not enter your email address.';
$hasError = true;
} else if( !preg_match( "/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim( $_POST['email'] ) ) ) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim( $_POST['email'] );
}
if( trim( $_POST['phone'] ) === '' ) {
$phoneError = 'You did not enter your telephone number.';
$hasError = true;
} else if( !is_numeric( $_POST['phone'] ) ) {
$phoneError = 'You have entered an invalid phone number.';
$hasError = true;
} else {
$phone = trim( $_POST['phone'] );
}
if( !empty( $_POST['required'] ) ) {
$requiredError = 'You appear to be a robot. If you are human, please try again.';
$hasError = true;
}
if( !isset( $hasError ) ) {
$subject = 'Call Back Request from ' . $name;
$body = "Name: $name \n\nEmail: $email \n\nPhone: $phone";
$headers = 'From: ' . $name . ' <' . $emailTo . '>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail( $to, $subject, $body, $headers );
$emailSent = true;
}
}
?>
<?php get_header(); ?>
<div class="content" role="main">
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php if( isset( $emailSent ) && $emailSent == true ) { ?>
<p><strong>Your message has been sent successfully. Someone will be in touch shortly. Thanks.</strong></p>
<?php the_content(); ?>
<?php } else { ?>
<?php if( isset( $hasError ) ) { ?>
<p class="error">Sorry, an error has occured.<p>
<ul>
<?php if( $nameError != '' ) { ?>
<li>
<span class="error"><?php echo $nameError; ?></span>
</li>
<?php } ?>
<?php if( $emailError != '' ) { ?>
<li>
<span class="error"><?php echo $emailError; ?></span>
</li>
<?php } ?>
<?php if( $phoneError != '' ) { ?>
<li>
<span class="error"><?php echo $phoneError; ?></span>
</li>
<?php } ?>
<?php if( !empty( $requiredError ) ) { ?>
<li>
<span class="error"><?php echo $requiredError; ?></span>
</li>
<?php } ?>
</ul>
<?php } ?>
<?php the_content(); ?>
<?php } ?>
</div>
</div>
<?php endwhile; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
OK Guys,
Looks like I've finally figured out the problem. All the code, in all it's variations was fine and works, except for one tiny thing. The variable '$name' is used by the WordPress system to display the blog name, and as I was using that as my variable for the name field on my form it was causing issues. Who knew.
Anyway, I simply changed it to use '$fullName' and changed the id and name attributes on the form to 'full-name' and everything worked great.
Thanks to #maiorano84 for pointing me in the right direction to debug the problem.
Anyway, below is my amended code, so others can make use of it.
Form Code
<form name="quick-contact" class="quick-contact" method="post" action="<?php bloginfo( 'url' ); ?>/get-in-touch/">
<h3>Request a Call Back</h3>
<h4><label for="full-name">Full Name</label></h4>
<input id="full-name" name="full-name" type="text" />
<h4><label for="email">Email</label></h4>
<input id="email" name="email" type="text" />
<h4><label for="phone">Phone</label></h4>
<input id="phone" name="phone" type="text" />
<input id="submit" type="submit" value="Submit" />
<input type="hidden" name="required" id="required" class="required" />
</form>
PHP Code
<?php
/*
* Template Name: Contact
*/
?>
<?php get_header(); ?>
<?php
if( $_SERVER['REQUEST_METHOD'] == "POST" ) {
$to = get_option( 'admin_email' );
if( trim( $_POST['full-name'] ) === '' ) {
$nameError = 'You did not enter your name.';
$hasError = true;
} else {
$fullName = trim( $_POST['full-name'] );
}
if( trim( $_POST['email'] ) === '' ) {
$emailError = 'You did not enter your email address.';
$hasError = true;
} else if( !preg_match( "/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim( $_POST['email'] ) ) ) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim( $_POST['email'] );
}
if( trim( $_POST['phone'] ) === '' ) {
$phoneError = 'You did not enter your telephone number.';
$hasError = true;
} else if( !is_numeric( $_POST['phone'] ) ) {
$phoneError = 'You have entered an invalid phone number.';
$hasError = true;
} else {
$phone = trim( $_POST['phone'] );
}
if( !empty( $_POST['required'] ) ) {
$requiredError = 'You appear to be a robot. If you are human, please try again.';
$hasError = true;
}
if( !isset( $hasError ) ) {
if ( !isset( $to ) || ( $to == '' ) ) {
$to = get_option( 'admin_email' );
}
$subject = 'Call Back Request from ' . $fullName;
$body = "Name: $fullName <br />Email: $email <br />Phone: $phone";
$headers[] = 'From: ' . $fullName . ' <' . $email . '>';
$headers[] = 'Reply-To: ' . $email;
$headers[] = 'Content-type: text/html; charset=utf-8';
wp_mail( $to, $subject, $body, $headers );
$emailSent = true;
}
}
?>
<div class="content" role="main">
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php if( isset( $emailSent ) && $emailSent == true ) { ?>
<p><strong>Your message has been sent successfully. Someone will be in touch shortly. Thanks.</strong></p>
<?php } else { ?>
<?php var_dump($headers); ?>
<?php if( isset( $hasError ) ) { ?>
<p class="error">Sorry, an error has occured.<p>
<ul>
<?php if( $nameError != '' ) { ?>
<li>
<span class="error"><?php echo $nameError; ?></span>
</li>
<?php } ?>
<?php if( $emailError != '' ) { ?>
<li>
<span class="error"><?php echo $emailError; ?></span>
</li>
<?php } ?>
<?php if( $phoneError != '' ) { ?>
<li>
<span class="error"><?php echo $phoneError; ?></span>
</li>
<?php } ?>
<?php if( !empty( $requiredError ) ) { ?>
<li>
<span class="error"><?php echo $requiredError; ?></span>
</li>
<?php } ?>
</ul>
<?php } ?>
<?php } ?>
<?php the_content(); ?>
</div>
</div>
<?php endwhile; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Tell me if is arrived an email, if not change
$to = get_option( 'admin_email' );
with
$to = your#email.com; //exemple
When you have changed try and tell me if it works ;)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
EDIT/UPDATE:
I moved my php code from my process.php file to the top of my contact.php file and it worked. So what am I missing from the process.php file that is not redirecting it back to the contact.php page?
This is my html in contact.php
<?php echo $message; ?>
<form action="process.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" required/>
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" required/><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" required/><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" required/>
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" required/>
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" required/>
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" required/>
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php echo $success_message; ?>
</form>
And this is my process.php
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
}
}
It is not working. Also the html5 validation isn't even working either. Is there something wrong with my form markup?
When you click on submit, your browser navigates to process.php. All of the code from contact.php is forgotten and a new page is generated.
There is no implied link between the two pages. The messages from process.php will not apppear on contact.php. Currently, process.php doesn't echo anything, so you're probably arriving at a blank page.
An alternate way to do this would be to merge the two pages like this:
<?php
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
//don't clear this, you need this to re-populate the page below
//unset($_POST);
}
}
?><!doctype html>
<html>
<head>
...
</head>
<body>
<?php echo $message; ?>
<form action="contact.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" required/>
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" required/><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" required/><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" required/>
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" required/>
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" required/>
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" required/>
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php echo $success_message; ?>
</form>
</body>
</html>
The $message and $success_message variables are now saved and they should display in the page markup below.
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message = "Please include your first name. ";
echo $message;
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message = "Please include your last name. ";
echo $message;
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message = "Please include your billing address. ";
echo $message;
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message = "Please enter a city. ";
echo $message;
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message = "Please select a state. ";
echo $message;
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message = "Please include a zip code. ";
echo $message;
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message = "Please include your phone number. ";<
echo $message;
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message = "A valid email is required. ";
echo $message;
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message = "You forgot to select a service package. ";
echo $message;
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
echo $success_message;
//clear form when submission is successful
unset($_POST);
}
}
i added echo $message for echoing during validation and .= was i think wrong way, otherwise you would have a message that contains all error messages..
Try adding this after the unset( $_POST ) line:
header('Location: contact.php');
That should take you back to the contact.php page.
EDIT:
However, in order for your code completely to work the way you want it, here what I would do.
<?php
session_start();
if (isset ($_SESSION['message'])) {
echo $_SESSION['message'];
session_destroy();
}
?>
<form action="process.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" />
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" /><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" /><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" />
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" />
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" />
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" />
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php
//session already started on line 2
if (isset( $_SESSION['success'] )) {
echo $_SESSION['success'];
session_destroy();
}
?>
</form>
That's for contact.php, and
<?php
//when submit has been pressed, begin form validate else return to contact.php
if ( $_SERVER[ 'REQUEST_METHOD' ] == "POST" ) {
session_start();
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
$_SESSION['success']=$success_message;
}
else {
$_SESSION['message'] = $message;
}
header('Location: contact.php');
} // end of if ( $_SERVER[ 'REQUEST_METHOD' ] == "POST" )
else header('Location: contact.php');
?>
process.php
The following control I think was creating the biggest confusion in your code:
//when submit has been pressed, begin form validate
if(isset($_POST['submit']))
as soon as I replaced it, everything started to work better.
I am new to the world of coding and PHP. Having picked up some of the basics, I have put a form together. I'm sure there are much efficient ways to code a page however seeing I have put something together with what I have learnt so far, I am having troubling getting past on select a multi-select dropdown after the user has posted the page i.e. to remember what the user selected. Here is my entire code.
<?php
//Process form variables
//Validate if the form has been submitted
if(isset($_POST['submit'])) {
//Validate if the form elements were completed
$fname = isset($_POST['fname']) ? $_POST['fname'] : '';
$lname = isset($_POST['lname']) ? $_POST['lname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$gender = isset($_POST['gender']) ? $_POST['gender'] : '';
$updates = isset($_POST['updates']) ? $_POST['updates'] : '';
$media = isset($_POST['media']) ? $_POST['media'] : '';
$comments = isset($_POST['comments']) ? $_POST['comments'] : '';
//Place error messages in an array
$errormsg = array();
if(empty($fname)) {
$errormsg[0] = 'Please specify your first name. It\'s blank.';
}
if(empty($lname)) {
$errormsg[1] = 'Please specify your last name. It\'s blank.';
}
if(empty($email)) {
$errormsg[2] = 'Please provide an email address. It\'s blank.';
}
if(empty($gender)) {
$errormsg[3] = 'Please select a gender. It\'s blank.';
}
if(empty($updates)) {
$errormsg[4] = 'Please select how we can contact you. It\'s blank.';
}
if(empty($media)) {
$errormsg[5] = 'Please select where you heard about us. It\'s blank.';
}
if(empty($comments)) {
$errormsg[6] = 'Please tell us what you think of us. It\'s blank.';
}
//Return list of error messages
foreach($errormsg as $errormsg) {
echo $errormsg . '<br />';
}
//Debug
print_r($_POST['media']);
}
?>
<html>
<head>
<title>Sample Registration Form</title>
</head>
<body>
<h2>Sample Registration Form</h2>
<form name="registration" method="post" action="registration.php">
<div>
First Name: <br />
<input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>">
</div>
<div>
Last Name: <br />
<input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>">
</div>
<div>
Email Address: <br />
<input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>">
</div>
<div>
Gender: <br />
<?php
//Generate gender array
$gender = array('male', 'female');
$countgender = count($gender);
for($start=0;$start < $countgender;$start=$start+1) {
$status = '';
if(isset($_POST['submit'])) {
if($_POST['gender'][0] == $gender[$start]) {
$status = 'checked';
// echo $gender[$start];
}
}
$genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start];
echo $genderform;
}
// foreach($gender as $gender) {
// $status = '';
// if(isset($_POST['submit'])) {
// if($_POST['gender'][0] == $gender) {
// $status = 'checked';
// }
// }
// $genderform = '<input type="radio" name="gender[]" value="' .$gender . '" ' . $status .'>'. $gender . '';
// echo $genderform;
// }
?>
</div>
<div>
Would you like to receive updates from us? <br />
<?php
$updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms');
foreach($updates as $updatekeys => $updatevalues) {
$status = '';
if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) {
$status = 'checked';
// echo $_POST['updates'][$updatevalues];
}
echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues;
}
?>
</div>
<div>
How did you hear about us? <br />
<select name="media[]" multiple>
<?php
$media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($media as $mediakey => $mediavalue) {
$mediaform = '<option value="'. $mediavalue . '">'.$mediavalue.'</option>';
echo $mediaform;
}
?>
</select>
</div>
<div>
Tell us what you think: <br />
<textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea>
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
</body>
</html>
EDIT
Guys, I have updated my code to reflect some of the suggestions below. Let me know if the page is better coded. I have not included suggestions such as $start++ just because I am trying to understand what it means. I love to make coding as short as possible but seeing that I am just learning, best to get a good foundation.
<?php
//Initialize session
session_start();
//Generate session id
echo session_id() . '<br />';
//Process form variables
//Validate if the form has been submitted
if(isset($_POST['submit'])) {
//Validate if the form elements were completed
$fname = isset($_POST['fname']) ? $_POST['fname'] : '';
$lname = isset($_POST['lname']) ? $_POST['lname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$gender = isset($_POST['gender']) ? $_POST['gender'] : '';
$updates = isset($_POST['updates']) ? $_POST['updates'] : '';
$media = isset($_POST['media']) ? $_POST['media'] : '';
$comments = isset($_POST['comments']) ? $_POST['comments'] : '';
//Place error messages in an array
$errormsg = array();
if(empty($fname)) {
$errormsg[0] = 'Please specify your first name. It\'s blank.';
}
if(empty($lname)) {
$errormsg[1] = 'Please specify your last name. It\'s blank.';
}
if(empty($email)) {
$errormsg[2] = 'Please provide an email address. It\'s blank.';
}
if(empty($gender)) {
$errormsg[3] = 'Please select a gender. It\'s blank.';
}
if(empty($updates)) {
$errormsg[4] = 'Please select how we can contact you. It\'s blank.';
}
if(empty($media)) {
$errormsg[5] = 'Please select where you heard about us. It\'s blank.';
}
if(empty($comments)) {
$errormsg[6] = 'Please tell us what you think of us. It\'s blank.';
}
//Return list of error messages
foreach($errormsg as $errormsg) {
echo $errormsg . '<br />';
}
//Debug
// print_r($_POST['media']);
}
?>
<html>
<head>
<title>Sample Registration Form</title>
</head>
<body>
<h2>Sample Registration Form</h2>
<form name="registration" method="post" action="registration.php">
<div>
First Name: <br />
<input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>">
</div>
<div>
Last Name: <br />
<input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>">
</div>
<div>
Email Address: <br />
<input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>">
</div>
<div>
Gender: <br />
<?php
//Generate gender array
$gender = array('male', 'female');
$countgender = count($gender);
for($start=0;$start < $countgender;$start=$start+1) {
$status = '';
if(isset($_POST['submit']) && !empty($_POST['gender'])) {
$status = in_array($gender[$start], $_POST['gender']) ? 'checked' : '';
}
$genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start];
echo $genderform;
}
?>
</div>
<div>
Would you like to receive updates from us? <br />
<?php
$updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms');
foreach($updates as $updatekeys => $updatevalues) {
$status = '';
if(isset($_POST['submit']) && !empty($_POST['updates'])) {
$status = in_array($updatevalues, $_POST['updates']) ? 'checked' : '';
}
// if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) {
// $status = 'checked';
// echo $_POST['updates'][$updatevalues];
// }
echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues;
}
?>
</div>
<div>
How did you hear about us? <br />
<select name="media[]" multiple>
<?php
$media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($media as $mediakey => $mediavalue) {
$status = in_array($mediavalue,$_POST['media'])? 'selected' : '';
$mediaform = '<option value="'. $mediavalue . '" '. $status .'>'.$mediavalue.'</option>';
echo $mediaform;
}
?>
</select>
</div>
<div>
Tell us what you think: <br />
<textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea>
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
</body>
</html>
You can use in_array function to check whether the current $mediavalue in the array of selected $media - but you need to select another name for array with media sources, because it overwrites the $media variable with user selection. For example:
$mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($mediaTypes as $mediakey => $mediavalue) {
$mediaform = '<option value="'. $mediavalue . '" '
. (in_array($mediavalue, $media) ? 'selected' : '') . '>' . $mediavalue.'</option>';
echo $mediaform;
}
There are a few recommended minor modifications to you code as well:
you do not need to use numbers in array - it duplicates the default behavior, so $mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure'); can be just $mediaTypes = array('internet', 'pamphlet', 'brochure');
when gender is not set, $_POST['gender'] causes notice "Undefined index: gender".
$start=$start+1 can be compacted to $start++;
it is better to reuse the variables with user inputs instead of accessing $_POST directly
Try this:
foreach($media as $mediakey => $mediavalue) {
$selected=in_array($mediavalue,$_POST['media'])?"selected":"";
$mediaform = '<option '.$selected.' value="'. $mediavalue . '">'.$mediavalue.'</option>';
echo $mediaform;
}
based on form output of the dropdown, set a $_SESSION['variable'] the do something like:
if (isset($_SESSION['variable'])) {
// if exists
}
else {
// if doesn't exist
}
you could even include other elseif statements based on different parameters. Then use else as an error handle.