I created an AMP page for my website, all works fine on my desktop browser, tested and works fine on my mobile, if certain fields are empty or not valid, the submit-error correctly displays the error message, also, on successful submission it correctly displays the submit-success message.
When I submitted the page to Google to cache the amp page, I tested the form once again, this time it isn't displaying the error or success messages. But if the form submission is valid, it will send me an email but not display the success message.
Form html code:
<form action-xhr="posts/submit.php" method="POST" class="contactForm" target="_top">
<fieldset>
<div class="formFieldWrap">
<label class="field-title">Select a product:<span>(required)</span></label>
<div class="select-style full-bottom">
<select name="product">
<option selected="" disabled="">Select a Product</option>
<option value="product1">product 1</option>
<option value="product2">product 2</option>
</select>
</div>
</div>
<div class="formFieldWrap">
<label class="field-title">Full Name:<span>(required)</span></label>
<input type="text" name="fullname" value="" class="contactField" />
</div>
<div class="formFieldWrap">
<label class="field-title">Telephone: <span>(required)</span></label>
<input type="text" name="telephone" value="" class="contactField" />
<div class="formFieldWrap">
<label class="field-title">Email: <span>(required)</span>
</label>
<input type="text" name="email" value="" class="contactField" />
</div>
<input type="hidden" name="ps" value="amp_Homepage">
<div class="formSubmitButtonErrorsWrap contactFormButton">
<input type="submit" class="buttonWrap button bg-teal-dark contactSubmitButton" value="Start my claim" />
</div>
</fieldset>
<div submit-success>
<template type="amp-mustache">
<span class="center-text color-green-dark"><strong>Congratulations {{fullname}}!</strong> You have successfully submitted your claim. You can expect a telephone call from My Claim Solved just to confirm a few details.</span>
</template>
</div>
<div submit-error>
<template type="amp-mustache">
<span class="center-text color-red-light"><strong>Oops!</strong> {{message}}</span>
</template>
</div>
</form>
PHP page:
<?php
$source_origin = trim($_REQUEST['__amp_source_origin']);//Security
if($source_origin != "https://example.com"){
echo "Not allowed origin";
return;
}
header('AMP-Access-Control-Allow-Source-Origin: https://example.com');
header('Content-Type: application/json; charset=UTF-8;');
$start = microtime(true);
$con=mysqli_connect("myip","myuser","mypass","mydb");
$Product = mysqli_real_escape_string($con, $_REQUEST['product']);
$FullName = mysqli_real_escape_string($con, $_REQUEST['fullname']);$FullName = ltrim($FullName);$FullNameMail = mysqli_real_escape_string($con, $_REQUEST['fullname']);
$Telephone = mysqli_real_escape_string($con, $_REQUEST['telephone']);
$Email = mysqli_real_escape_string($con, $_REQUEST['email']);
$Provider = mysqli_real_escape_string($con, $_REQUEST['provider']);
$PageSource = mysqli_real_escape_string($con, $_REQUEST['ps']);
if($Product != 'product1' && $Product != 'product2'){
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must select a product.'));
}elseif(empty($FullName) || strlen($FullName)<3) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter your full name.'));
}elseif (empty($Telephone) || strlen($Telephone)<9) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter a valid telephone number.'));
}elseif (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter a valid email address.'));
}else{
// Send Email
$To = "myemail#example.com";
$Message = "bla bla";
$Headers = "From: myemail#example.com";
mail($To, 'subject bla', $Message, $Headers);
echo json_encode(array("product"=>$Product,"fullname"=>$FullName,"telephone"=>$Telephone,"email"=>$IPAddress));
}
?>
just to let you know how it was fixed (thanks to ade for pointing me in the right direction), I amended the headers on the php page to the below:
header("access-control-allow-credentials:true");
header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
header("access-control-allow-methods:POST, GET, OPTIONS");
header("access-control-allow-origin:".$_SERVER['HTTP_ORIGIN']);
header("access-control-expose-headers:AMP-Access-Control-Allow-Source-Origin");
header("amp-access-control-allow-source-origin:https://".$_SERVER['HTTP_HOST']);
header("Content-Type: application/json");
Related
I'm learning coding and created a simple form where error messages are
displayed just below each input field. However, when I check the form
the success message appears at the same time as error messages instead
of displaying when all the fields are correctly entered and form
validated. Can you please help. Thank yo in advance. Here is my
code.
</php>
$errorMessage = "";
$successMessage = "";
$emailError = "";
$emailconfirmError = "";
$nameError = "";
$messageError = "";
$servicesError = "";
$name = $email = $emailConfirm = $services = $message = "";
$email = isset($_POST['email']) ? $_POST['email'] : '';
$emailConfirm = isset($_POST['emailConfirm']) ? $_POST['emailConfirm'] : '';
if ($_POST) {
if (!$_POST['email']) {
$emailError .="The email is required";
}
if (!$_POST['emailConfirm']) {
$emailconfirmError .="Please confirm your email <br>";
}
if ($_POST['emailConfirm'] && $email != $emailConfirm) {
$emailconfirmError .="The email addresses do not match <br>";
}
if (!$_POST['name']) {
$nameError .="The name field is required <br>";
}
if (!$_POST['services']) {
$servicesError .="Please select a service required <br>";
}
if (!$_POST['message']) {
$messageError .="The message field is required <br>";
}
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$emailError .= "The email address is invalid.<br>";
}
if ($name = $email = $emailConfirm = $services = $message != "") {
echo $emailError;
echo $emailconfirmError;
echo $name;
echo $services;
echo $message;
}else {
$emailTo = "kamala_guliyeva#hotmail.com";
$services = $_POST['services'];
$message = $_POST['message'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $services, $message, $headers)) {
$successMessage = '<div class="alert alert-success" role="alert">Thank you for your message. We\'ll get back to you ASAP!</div>';
} else {
$errorMessage = '<div class="alert alert-danger" role="alert"><p>Your message couldn\'t be sent - please try again</div>';
}
}
}
and HTML
<div id="quote">
<div class="container">
<h2 class="section-title">Request a Quote</h2>
<hr align="left" width="8%" class="style-one">
<br>
<div><? echo $errorMessage.$successMessage; ?></div>
<form id="quoteForm" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="email" name="email" placeholder="Your email">
<label class="error" id="emailError"><?php echo $emailError; ?></label>
</div>
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="emailConfirm" name="emailConfirm" placeholder="Re-type your email">
<label class="error" for="e-mailConfirm" id="emailconfirmError"><?php echo $emailconfirmError; ?></label>
</div>
<div class="form-group">
<input type="name" class="form-control" id="name" style="height:60px" name="name" placeholder="Your Name">
<label class="error" for="name" id="nameError"><?php echo $nameError; ?></label>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<select class="form-control" id="services" name="services" style="height:60px">
<option value="">Select Services</option>
<option value="Installation">Installation</option>
<option value="Repair">Repair</option>
<option value="Service and Maintenance">Service and Maintenance</option>
</select>
<label class="error" for="services" id="servicesError"><?php echo $servicesError; ?></label>
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Message" style="height: 163px;" cols="35"></textarea>
<label class="error" for="message" id="messageError"><?php echo $messageError; ?></label>
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button type="submit" style="width:10rem" class="btn quoteButton pt-3 pb-3 text-align-center">Get a Quote</button>
</div>
</div>
</form>
</div>
</div>
You've a few problems there...
So first thing is how you are doing your checks.
if(!$_POST) {
is not a valid way of checking that a post has occurred you need to do something like
if(isset($_POST) && !empty($_POST)) {
would be more appropriate as you are checking if the POST array is actually set and then that it is not empty the && operator is a short circuit operator so if either condition isn't met then the check will fail.
Similarly on your comparisons saying if(!$_POST['email']) { isn't valid because you're effectively asking "if the email part of the post array is not true" where as you need to be asking "if it's not blank and is a valid email address"
You need to be aware of the difference between = == and === operators. You can find some more information here: The 3 different equals
And also the filter_var function here: http://php.net/manual/en/function.filter-var.php
if($_POST['email']!=="" && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
//all good
} else {
//set your error message
}
you can use regular expressions to validate 'name' see preg_match in the manual http://php.net/manual/en/function.preg-match.php
Aside from all of this if you want to have real time monitoring of the fields and the error messages etc you're going to have to look at incorporating Javascript and using AJAX to communicate with your script and then parse the response back into the appropriate div.
Have a look at Rasmus 30 second AJAX tutorial will give you a starting point for this http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
However it is better practice to do both client and server side validation hope this helps even if it is not a complete answer per sé.
I'm trying to input form data into the database. I'm using almost the same code as I did for my registration script, which works perfectly. I'm completely stumped at this point.
I have error reporting turned on for PHP and PDO, nothing is happening. When the form is sent, it appears to work (except without the confirmation messages appearing) but nothing is entered into the database.
I have two files, request.php (the form) and parseRequest.php (the backend to the form).
request.php
<form action="" method="post">
<div class="form-group">
<input type="hidden" class="form-control" name="username" id="usernameField" value="<?php echo $_SESSION['username'];?>">
</div>
<div class="form-group">
<label>Headlining Band/Artist</label>
<input type="text" class="form-control" name="artist" id="artistField" placeholder="Artist">
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" name="day" id="dateField" placeholder="MM/DD/YYYY">
</div>
<div class="form-group">
<label>Venue</label>
<input type="text" class="form-control" name="venue" id="venueField" placeholder="Venue">
</div>
<div class="form-group">
<label>City, State</label>
<input type="text" class="form-control" name="city" id="cityField" placeholder="City, State">
</div>
<input type="hidden" name="token" value="<?php if(function_exists('_token')) echo _token(); ?>">
<button type="submit" name="requestBtn" class="btn btn-primary pull-right">Submit</button>
parseRequest.php
<?php
include_once 'resource/Database.php';
include_once 'resource/utilities.php';
include_once 'resource/send-email.php';
// Processing the form
if(isset($_POST['requestBtn'], $_POST['token'])){
if(validate_token($_POST['token'])) {
//process form here
$form_errors = "";
// validation
$required_fields = array('artist', 'day', 'venue', 'city');
// check empty fieldset
$form_errors = check_empty_fields($required_fields);
// date check
$fields_to_check_length = array('day' => 10);
//call the function to check minimum required length and merge the return data into form_error array
$form_errors = array_merge($form_errors, check_min_length($fields_to_check_length));
// collect data
$username = $_POST['username'];
$artist = $_POST['artist'];
$day = $_POST['day'];
$venue = $_POST['venue'];
$city = $_POST['city'];
}
else if(empty($form_errors))
{
// preparing and inputting data
try
{
$sqlInsert = "INSERT INTO requests(username, artist, day, venue, city)
VALUES (:username, :artist, :day, :venue, :city)";
//use PDO prepared to sanitize data
$statement = $db->prepare($sqlInsert);
//add the data into the database
$statement->execute(array(':username' => $username, ':artist' => $artist, ':day' => $day, ':venue' => $venue, ':city' => $city));
// email confirmation
$addresses = array($_SESSION['email'], 'codylkaczynski#gmail.com');
//prepare email body
$mail_body = '<html>
<body style="font-family: Arial, Helvetica, sans-serif;
line-height:1.8em;">
<h2>Amped Sound Staff Portal: Request Received</h2>
<p>Dear '.$username.'<br><br>
Your request for the '.$artist.' show in '.$city.' on '.$date.' has been received!</p><br/>
<p>We will let you know if your request has been approved or denied ASAP.</p><br/>
<p>Thank you!</p><br/>
<p><strong>©2018 Amped Sound</strong></p>
</body>
</html>';
$namejeff = explode(',', $addresses);
foreach ($addresses as $address)
{
$mail->AddAddress($address);
$mail->Subject = "Request Received!";
$mail->Body = $mail_body;
}
//Error Handling for PHPMailer
if(!$mail->Send())
{
$result = "<script type=\"text/javascript\">swal(\"Error\",\" Email sending failed: $mail->ErrorInfo \",\"error\");</script>";
}
else
{
$result = "<script type=\"text/javascript\">
swal({
title: \"Request received!\",
text: \"We have received your request! Please check your email for confirmation.\",
type: 'success',
confirmButtonText: \"Thank You!\" });
</script>";
}
}
catch (PDOException $ex)
{
$result = flashMessage("An error occurred: " .$ex->getMessage());
}
}
}
I appreciate any help I can get. I've tried a bunch of solutions I found on StackOverflow already, to no avail.
I have an html from. When the user submits the form, I'm sending an email to the given email address using php. Emails to gmail accounts go through perfectly fine. However, mails to providers like yahoo, aol etc does not go through.There is no filter mechanism in my code to filter out email addresses. Some mails to yahoo mail addresses goes through rarely. But aol doesn't go at all. What is the issue here?
My html code:
<section class="contact-container">
<div class="container mtb">
<div class="row">
<div class="col-md-8 wow fadeInLeft">
<h4>Get in touch</h4>
<hr>
<p>Leave a comment, review, or general musings.
</p><br/>
<form method="post" id="captcha_form" name=
"captcha_form" action="mailform.php"><fieldset><ol>
</li><li><label class="solo" for="email">Email address:</label>
<span class="required">(required)</span><input type="text" class="solo
input" name="email" id="email" value="" />
</li><li><label class="solo" for="name">Name:</label><input type=
"text" class="solo input" name="name" id="name" value="" />
</li><li><label class="solo" for="subject">Subject:</label>
<span class="required">(required)</span> <input type="text" class=
"solo input" name="subject" id="subject" />
</li><li><label class="solo" for="message">Message:</label>
<span class="required">(required)</span>
<div class="solo input"><textarea class="solo input" name="message" id=
"message" ></textarea><br />
<p><input name="submit" id="submit" type="submit" value="Send" style=
"float: right;" /></p></div>
</li></ol>
</fieldset></form> <br /> <br />
</div>
And here is snippets of mailform.php:
<?php
$dontsendemail = 0;
$possiblespam = FALSE;
$strlenmessage = "";
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$subject = $_REQUEST['subject'];
$emailaddress = "email#gmail.com";
/ Check human test input box
if(isset($_REQUEST["htest"]) && $_REQUEST["htest"] != "") die
("Possible spam detected. Please hit your browser back button
and check your entries.");
// Check email address function
function checkemail($field) {
// checks proper syntax
if( !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+
([a-zA-Z0- 9._-]+)+$/", $field))
{
die("Improper email address detected. Please hit your browser back
button and enter a proper email address.");
return 1;
}
}
// Spamcheck function
function spamcheck($field) {
if(preg_match("/to:/i",$field) || preg_match("/cc:/i",$field)
|| preg_match("/\r/i",$field) || preg_match("/i\n/i",$field)
|| preg_match("/%0A/i",$field)){
$possiblespam = TRUE;
}else $possiblespam = FALSE;
if ($possiblespam) {
die("Possible spam attempt detected. If this is not the case, please
editthe content of the contact form and try again.");
return 1;
}
}
if ($dontsendemail == 0) {
$message="";
$message.="Name: ".$name."\r\n";
$message.="Mailing Address: \r\nLine 1: ".$addressline1."\r\nLine
2: ".$addressline2."\r\nCity: ".$city."\r\nState: ".$state."
\r\nZip: ".$zip."\r\n";
$message=$message."\r\nMessage:\r\n".$_REQUEST['message'];
mail($emailaddress,"$subject",$message,"From: $email" );
include "email_sent.php";
echo "Thank you, I will respond shortly.";
}
Don't use a regex to confirm email addresses. The real regex is like a day long. Use http://www.w3schools.com/php/filter_validate_email.asp or https://code.google.com/p/php-smtp-email-validation/ or https://github.com/appskitchen/emailverifier/blob/master/class.emailverify.php . You'll notice they are much more complicated than a basic regex. The email spec is insane: https://www.rfc-editor.org/rfc/rfc2822
It's a simple code but i can't understand where is my mistake. I want to display succesfull message under the form when i click the submit but the message stays there all the time. When i enter in the page where the form is the message is under the form. How to take it out only when the query is succesfull ?
<?php
$posted = false;
if(isset($_POST['add']))
{
$posted = true;
$email = $_POST['email'];
$name = $_POST['name'];
$rate = $_POST['rate'];
$comment = $_POST['comment'];
$dth = date("Y-m-d H:i:s");
$q = "INSERT INTO reviews(email, name, rate, comment, date_created) VALUES ('$email', '$name', '$rate', '$comment', '$dth')";
$k = mysqli_query($con,$q);
}
?>
<body>
<h1>Leave a review</h1>
<div class="error-conteiner">
</div>
<div class="clear"></div>
<form action="" method="post" class="form-content">
<div class="left">
<div class="field">
<label>E-mail <span class="required">*</span></label>
<input type="text" value="" name="email" class="required-field" data-validate="email"/>
</div>
<div class="clear"></div>
<div class="field">
<label>Name</label>
<input type="text" value="" name="name"/>
</div>
<div class="clear"></div>
<div class="field">
<label>Rate</label>
<select name="rate">
<option value=''>Choose rate</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
</div>
<div class="left">
<label>Comment <span class="required">*</span></label>
<textarea name="comment" class="comment required-field"></textarea>
</div>
<input type="submit" value="Send" class="btn" name="add" />
</form>
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
</body>
</html>
Maybe it is not professional and nice solution, but works well, if you make a query after the post with ex. $email and $name or other parameters. If the result is not empty, then you can put the results or just a simple message also into the output.
Replace
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
with
<?php
if($posted===true){
if($k) echo "Thank you for your comment!";
else die(mysqli_error());
}
?>
Maybe you have to put {} after your first if
Directly below:
$k = mysqli_query($con,$q);
add:
if(!$k) {
die(mysqli_error());
}
If the query wasn't executed, for whatever reason, show the error and stop.
You might consider adding a development mode variable or constant, because the mysqli_error() message is only valuable for the developer and the content is not for your users eyes. Anyway:
Replace:
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
with:
if($posted === true) {
echo 'Thank you for your comment!';
}
The mysql error is handled, where it occurs.
The success message is only displayed, when successfully send.
It's also possible to make a header redirection on success. But that depends, on what you like.
if($posted === true) {
header('Location: success-message-page.php');
exit;
}
I'm trying to get a form pre-filled using a query string and let the user make any necessary changes then press submit and have the form process and send an email to an administrator for doing whatever it is they need to do with the information.
I'm using PHP to populate the form and I started with a tutorial from NetTuts for the email form processing because it did validation inline. Hopefully validation isn't necessary because all the fields are pre-filled but I wanted to have the form check just to make sure the user doesn't clear a field before submitting the form. I'm at a loss as to why the form won't process correctly.
The only changes between my form and the tutorial are in variable names, the inclusion and some $_GET superglobals to grab the form data from the query string, and the use of echo to fill out the form from the $_GET superglobals instead of the session data should the user submit the form without filling everything out. Everything else has been copied verbatim from the tutorial.
Any help solving this problem, even if it's rethinking how I might go about doing this, would be much appreciated.
Below is the code for the form page and the processing page.
Form Page:
<?php
session_start();
// site root folder
$root_folder = "/meetingplannersignup";
//get values of displayed form fields from URL
$FirstName= $_GET['FirstName'];
$LastName = $_GET['LastName'];
$Organization = $_GET['Organization'];
$EmailAddress = $_GET['EmailAddress'];
$Phone = $_GET['Phone'];
$EventType = $_GET['EventType'];
$EventName = $_GET['EventName'];
$EventLocation = $_GET['EventLocation'];
$HotelName = $_GET['HotelName'];
$EventStart = $_GET['EventStart'];
$EventEnd = $_GET['EventEnd'];
// get values of hidden form fields from URL
$ExtReferenceID = $_GET['ExtReferenceID'];
$City = $_GET['City'];
$State = $_GET['State'];
$ZipCode = $_GET['ZipCode'];
$CountryCode = $_GET['CountryCode'];
?>
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Simplify Event Management with GroupMAX</title>
<link rel="stylesheet" href="<?php echo $root_url ?>/assets/css/bootstrap.css">
</head>
<body>
<div class="container">
<!-- begin main nav -->
<nav class="navbar navbar-static-top navbar-inverse" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-main-collapse">
<ul class="nav navbar-nav">
<li class="active">home</li>
<li>fill out form</li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
<!-- end main nav -->
<div class="row">
<div class="col-lg-12">
<h1>Simplify Event Management with GroupMAX</h1>
<h3>Impress Your Attendees. Optimize Your Event.</h3>
<hr />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<h4>Included Features are:</h4>
<ul>
<li><strong>Event Booking Websites – </strong>Passkey’s award winning booking website allows for personalized hotel reservation website where attendees can make, modify or cancel their hotel bookings directly into that group's contracted block.</li>
<li><strong>Integrated with Event Registration - </strong>RegLink™ is an integration technology that can link any online planner registration solution to Passkey's best-in-class hotel reservation system, allowing meeting planners to integrate hotel reservations directly into their event registration process.</li>
<li><strong>Event Dashboard – </strong>With Event Dashboard Planners can track their events, manage their lists and monitor reservations anytime online. With Passkey’s LiveView Dashboards, meeting planners can get an instant snapshot of their event in a fun, interactive environment. </li>
<li><strong>SmartAlerts™ - </strong>Automatic e-mails containing vital event information that are automatically sent out to a list of recipients at specific intervals or critical event milestones.</li>
</ul>
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- begin error processing -->
<div class="well">
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<div id="errors" class="alert alert-danger<?php echo ($sr && !$cf['form_ok']) ? ' show_alert' : ''; ?>">
<p>There were some problems with your form submission:</p>
<ul>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
</ul>
</div>
<p id="success" class="alert alert-success<?php echo ($sr && $cf['form_ok']) ? ' show_alert' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>
<!-- end error processing -->
<!-- begin form -->
<fieldset>
<legend>Your Information</legend>
<p>Please review the pre-filled information and correct any inaccurate information prior to submitting the form.</p>
<form method="post" action="process.php">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" id="FirstName" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['FirstName'] : '' ?><?php echo $FirstName; ?>">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" id="LastName" value="<?php echo $LastName; ?>">
</div>
<div class="form-group">
<label>Company/Organization</label>
<input type="text" class="form-control" id="Organization" value="<?php echo $Organization; ?>">
</div>
<div class="form-group">
<label>Email Address</label>
<input type="text" class="form-control" id="EmailAddress" value="<?php echo $EmailAddress; ?>">
</div>
<div class="form-group">
<label>Phone Number</label>
<input type="text" class="form-control" id="Phone" value="<?php echo $Phone; ?>">
</div>
<div class="form-group">
<label>Event Type</label>
<input type="text" class="form-control" id="EventType" value="<?php echo $EventType; ?>">
</div>
<div class="form-group">
<label>Event Name</label>
<input type="text" class="form-control" id="EventName" value="<?php echo $EventName; ?>">
</div>
<div class="form-group">
<label>Event Location</label>
<input type="text" class="form-control" id="EventLocation" value="<?php echo $EventLocation; ?>">
</div>
<div class="form-group">
<label>Hotel Name</label>
<input type="text" class="form-control" id="HotelName" value="<?php echo $HotelName; ?>">
</div>
<div class="form-group">
<label>Start/Arrival Date</label>
<input type="text" class="form-control" id="EventStart" value="<?php echo $EventStart; ?>">
</div>
<div class="form-group">
<label>End Date</label>
<input type="text" class="form-control" id="EventEnd" value="<?php echo $EventEnd; ?>">
</div>
<hr />
<input type="submit" value="Submit" class="btn btn-primary" />
<!--hidden fields-->
<input type="hidden" id="ExtReferenceID" value="<?php echo $ExtReferenceID; ?>">
<input type="hidden" id="City" value="<?php echo $City; ?>">
<input type="hidden" id="State" value="<?php echo $State; ?>">
<input type="hidden" id="ZipCode" value="<?php echo $ZipCode; ?>">
<input type="hidden" id="CountryCode" value="<?php echo $CountryCode; ?>">
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</fieldset>
</div>
<!-- end form -->
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Processing Page:
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//submission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Organization = $_POST['Organization'];
$EmailAddress = $_POST['EmailAddress'];
$Phone = $_POST['Phone'];
$EventType = $_POST['EventType'];
$EventName = $_POST['EventName'];
$EventLocation = $_POST['EventLocation'];
$HotelName = $_POST['HotelName'];
$EventStart = $_POST['EventStart'];
$EventEnd = $_POST['EventEnd'];
// hidden form fields
$ExtReferenceID = $_POST['ExtReferenceID'];
$City = $_POST['City'];
$State = $_POST['State'];
$ZipCode = $_POST['ZipCode'];
$CountryCode = $_POST['CountryCode'];
//validate form data
//validate First Name is not empty
if(empty($FirstName)){
$formok = false;
$errors[] = "You have not entered a First Name";
//validate Last Name is not empty
} elseif (empty($LastName)){
$formok = false;
$errors[] = "You have not entered a Last Name";
//validate Company/Organization is not empty
} elseif (empty($Organization)){
$formok = false;
$errors[] = "You have not entered a Company or organization";
//validate email address is not empty
} elseif (empty($EmailAddress)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
} elseif (!filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid Email Address";
//validate Last Name is not empty
} elseif (empty($Phone)){
$formok = false;
$errors[] = "You have not entered a Phone Number";
//validate Last Name is not empty
} elseif (empty($EventType)){
$formok = false;
$errors[] = "You have not entered an Event Type";
//validate Last Name is not empty
} elseif (empty($EventName)){
$formok = false;
$errors[] = "You have not entered an Event Name";
//validate Last Name is not empty
} elseif (empty($EventLocation)){
$formok = false;
$errors[] = "You have not entered an Event Location";
//validate Last Name is not empty
} elseif (empty($HotelName)){
$formok = false;
$errors[] = "You have not entered a Hotel Name";
//validate Last Name is not empty
} elseif (empty($EventStart)){
$formok = false;
$errors[] = "You have not entered an Event Start Date";
//validate Last Name is not empty
} elseif (empty($EventEnd)){
$formok = false;
$errors[] = "You have not entered an Event End Date";
}
//send email if all is ok
if($formok){
$headers = "From: meetingplannersignup#passkey.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new meeting planner signup registration:</p>
<p><strong>First Name: </strong> {$FirstName}</p>
<p><strong>Last Name: </strong> {$LastName}</p>
<p><strong>Company/Organization: </strong> {$Organization}</p>
<p><strong>Email Address: </strong> {$EmailAddress}</p>
<p><strong>Phone: </strong> {$Phone}</p>
<hr />
<p><strong>Event Type: </strong> {$EventType}</p>
<p><strong>Event Name: </strong> {$EventName}</p>
<p><strong>Event Location: </strong> {$EventLocation}</p>
<p><strong>Hotel Name: </strong> {$HotelName}</p>
<p><strong>Event Start Date: </strong> {$EventStart}</p>
<p><strong>Event End Date: </strong> {$EventEnd}</p>
<hr />
<p><strong>Reference ID: </strong> {$ExtReferenceID}</p>
<p><strong>City: </strong> {$City}</p>
<p><strong>State: </strong> {$State}</p>
<p><strong>Zip Code: </strong> {$ZipCode}</p>
<p><strong>Country Code: </strong> {$CountryCode}</p>
<hr />
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p> ";
mail("stuart#monderer.com","Meeting Planner Signup",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'FirstName' => $FirstName,
'LastName' => $LastName,
'EmailAddress' => $EmailAddress,
'Organization' => $Organization,
'Phone' => $Phone,
'EventType' => $EventType,
'EventName' => $EventName,
'EventLocation' => $EventLocation,
'HotelName' => $HotelName,
'EventStart' => $EventStart,
'EventEnd' => $EventEnd,
'ExtReferenceID' => $ExtReferenceID,
'City' => $City,
'State' => $State,
'ZipCode' => $ZipCode,
'CountryCode' => $CountryCode
),
'form_ok' => $formok,
'errors' => $errors
);
//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
//set session variables
session_start();
$_SESSION['cf_returndata'] = $returndata;
//redirect back to form
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
Several problems:
1. isset($_POST) will always be true
In your processing page you check for:
if( isset($_POST) )
This will always evaluate to true even if $_POST is empty. You should check for a specific field to try and guess is the form was submitted
2. You use id instead of name
The form values that are sent via POST are identified via their name, not via their id. In the HTML you can keep the id attribute but for each field that is to be POSTed you must add a name attribute:
<input type="text" class="form-control" name="LastName" id="LastName" value="<?php echo $LastName; ?>">
$_POST['LastName'] is empty if you only identify your form control with an id.
I haven't checked the rest but you should try to fix those points first.