PHP Contact Form Variations with Variables depending on Form - php

I was wondering someone could help me out with a best practice to achieve the following.
Please bare in mind I have very little experience with PHP, and am doing something more of a favour for a friend's company (his current developer is travelling and not due back until March).
He's put together 3 basic landing pages (each relevant to an industry), each has the exact same form on. The problem at the moment is the way they work is they all post to the same email address and have the same subject line (they all post to contact.php).
So what I'd like to do is add an IF statement, and perhaps put output a different $subject and $sendTo so they can be unique depending on each form. I've been having a look around and don't really want to have to create a new form and implement that, hopefully, I can just adjust what's here.
Here's contact.php
<?php
// an email address that will be in the From field of the email.
$from = 'Contact form <creative#email.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Contact form <creative#email.com>';
// subject of the email
$subject = 'Contact form enquiry from the Creative Services Landing Page';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'marketing' => 'Marketing');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
And here's the HTML
<form class="container" id="contact-form" method="post" action="contact.php" role="form">
<div class="row justify-content-md-center">
<div class="col-12 col-md-5 col-lg-4">
<div class="messages"></div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Your first name is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Your surname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="A valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-12 col-md-3 col-lg-2">
<button type="submit" class="btn btn--primary">Send</button>
</div>
</div>
</form>
Any help would be hugely appreciated!

You could give to every form a different value via $_GET:
<form class="container" id="contact-form" method="post" action="contact.php?landing_page=1" role="form">
And then depending of $_GET['landing_page'] value set $from, $sendTo and $subject variables:
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'marketing' => 'Marketing');
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
if (isset($_GET['landing_page']))
{
if ($_GET['landing_page'] == 1)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
elseif($_GET['landing_page'] == 2)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
elseif($_GET['landing_page'] == 3)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
else
{
throw new \Exception('Invalid landing_page value');
}
}
else
{
throw new \Exception('Invalid landing_page value');
}
/*
* LET'S DO THE SENDING
*/

Related

Issue with contact form displaying sent message on php rather than in html page

So I have tried searching for this issue and have tried many fixes but I still keep getting the same issue, "Contact form successfully submitted. Thank you, I will get back to you soon!" displays on php page rather than on the contact form html page, Im sure there is something very simple that I'm missing, I keep ending in stupid thought and search loops, I thank you all for any help you can offer.
$(function() {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$("#contact-form").validator();
// when the form is submitted
$("#contact-form").on("submit", function(e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "ebsg.php";
// FOR CODEPEN DEMO I WILL PROVIDE THE DEMO OUTPUT HERE, download the PHP files from
// https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
var messageAlert = "alert-success";
var messageText =
"Your message was sent, thank you. ebgs will get back to you soon.";
// let's compose Bootstrap alert box HTML
var alertBox =
'<div class="alert ' +
messageAlert +
' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
messageText +
"</div>";
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$("#contact-form").find(".message").html(alertBox);
// empty the form
$("#contact-form")[0].reset();
}
return false;
}
});
});
<?php
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '6LelY04iAAAAAN',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
echo '<p>Please go back and make sure you check the security CAPTCHA box.</p><br>';
} else {
// If CAPTCHA is successfully completed...
// configure
$from = 'ebsg contact form <ebsg#domain.com>';
$sendTo = 'ebsg contact form <email#yahoo.co.uk>';
$subject = 'ebsg contact form message';
$fields = array('name' => 'Name', 'surname' => 'Address', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from ebsg website contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
}
?>
<form id="contact-form" method="post" action="ebsg.php" role="form">
<div class="controls">
<div class="row">
<div class="col-md-6">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required>
</div>
<div class="col-md-6">
<label for="form_lastname">Address *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your address *" required>
</div>
<div class="col-md-6">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required>
</div>
<div class="col-md-6">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
</div>
<div class="col-md-12">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for EBSG *" rows="4" required></textarea>
</div>
<div class="col-md-6">
<div class="message"></div>
<div class="g-recaptcha" data-sitekey="6Lel478655677AACWfJGw0i2SDE9B-dbr-5mD6OHqG"></div>
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
<div class="col-md-6">
<p class="text-muted justify-content-center"><strong>*</strong> These fields are required.</p>
</div>
</div>
</div>
</form>

Sending email to multiple adressess PHP

I have an HTML form where you can enter your email and a message.
After you submit this form i would like an email to be sent to my email (fixed) and to the email that is filled in trough the form.
I got my email to work but i can't seem to get the email from my HTML form into the send list in PHP. Any suggestions?
Code (html):
<form id="contact-form" method="post" action="js/contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Vul hier je email adres in" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">message</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Vul hier een eventuele opmerking of message in." rows="4" required="required" data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Versturen">
</div>
</div>
</div>
</form>
Code PHP:
<?php
$from = 'info#mywebsite';
$sendTo = 'myemail#gmail.com'; //Here the email from the form should be added
$subject = 'Nieuwe reservering';
$fields = array('kosten' => 'kosten' , 'name' => 'Naam', 'surname' => 'Achternaam', 'phone' => 'Telefoonnummer', 'kamer' => 'Kamer', 'aankomst' => 'aankomst', 'vertrek' => 'vertrek', 'email' => 'Email', 'message' => 'Bericht');
$okMessage = 'Je bericht is verzonden!';
$errorMessage = 'Oei er ging iets fout, geeft niks. Probeer het later opnieuw.';
error_reporting(E_ALL & ~E_NOTICE);
try {
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText ="<table>";
$emailText .="<p>Bedankt voor uw reservering, hieronder de ingevulde info:</p><br><br>";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "<tr><td>{$fields[$key]}</td>";
$emailText .= "<td>$value</td></tr>";
}
}
$emailText .="<br><br><p>Voor vragen of wijzigingen mail naar: info#bmyemail</p>";
$emailText .="</tr></table>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers = array('Content-type:text/html;charset=UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e){
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
You can specify all recipients like this: (check official guideline here)
$sendTo = 'myemail#gmail.com, abc#example.com, xyz#example.com'; // note the comma
//actual message
$message = "Message Content";
mail($sendTo, $subject, $message));
Hope it helps! :)
After your email is done, you just need to send it twice :
<?php
mail($addr1, $subject, $message, $header);
mail($addr2, $subject, $message, $header);
?>
You can also concatenate differents addresses (I've managed to send a mail to different addresses by changing my input to a textarea and writing one address per line).
Good luck!

PHP Contact Form 403 Error

In the process of setting up a website for myself, i've hit a bit of a road block with the PHP contact form. I believe it is coded correctly, but whenever I upload it to my site and try to use the contact form I get "Page is forbidden 403". I'm using Hostinger by the way, i've set the permissions of my public_html file to 755. Not sure what the problem could be. Included is my code, any help would be greatly appreciated.
Contact code of the HTML from the index:
<div class="row stay-behind" id="contact">
<h4 class="right-name">Contact</h4>
<div class="col-md-1"></div>
<div class="col-sm-12 col-md-4 feature-image"><img alt="VX1K" height="510" src="images/ux/004.jpg" width="374"> <img alt="VX1K" class="mobile-only" src="images/ux/mobile/004.jpg"></div>
<div class="col-sm-12 col-md-6 main">
<h3 class="title">Contact</h3>
<form class="contact-form" id="contactForm" novalidate method="post" action="public_html/mail/contact_me.php">
<div id="form-alert"></div>
<div class="form-group">
<input class="form-control" id="name" name="name" placeholder="Name" type="name">
</div>
<div class="form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email">
</div>
<textarea class="form-control" id="message" placeholder="Message" rows="3"></textarea> <input class="btn btn-block btn-primary" id="btnSubmit" name="submit" type="submit" value="Send">
</form>
</div>
<div class="col-md-1"></div>
Code from the PHP file.
<?php
function Validate()
{
// Check for empty fields
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
return false;
}
else return true;
}
function SendEmail($to = 'noreply#vx1k.com')
{
if (Validate() == true)
{
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
// Create the email and send the message
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n" . "Here are the
details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#vx1k.com\n";
$headers.= "Reply-To: $email_address";
// Send true on successful send.
// Send false if failed
return (mail($to, $email_subject, $email_body, $headers)) ? true : false;
}
else
// Invalid inputs
return 'err';
}
// Apply function(s). You will get true, false, or err
$send = SendEmail();
// On return, you can echo any result
if ($send == 'err') echo 'Invalid Fields.';
elseif ($send == false) echo 'An Error Occurred.';
else echo 'Email Sent Successfully.';
?>

Bootstrap and PHP contact form display blank page when clicking submit [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
Hii guys I need some help.
When I try and test my bootstrap form, it displays a white screen. Here's my code.NB Am newbie to web developing, #ExcuseMyFrenchThough
Here is my index.html
<html>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" method="post" action="contact.php">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Your Name">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
<div class="form-group">
<textarea class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here"> </textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
<div class="form-group">
<button type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text">SEND MESSAGE</button>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
PHP CODE [CONTACT.PHP]
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage /*&& !$errHuman*/) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
Screenshot of what I get after I click submit on my page, NB live not local
anyone ?
The submit variable is never set in your form. Note the button is now an input of the type submit with the name attribute of submit.
Also your other form variables were not set.
You were never echoing anything. So i put an echo in your last condition.
If you want the form to display after submitting the form, you need to rename your index.html to index.php and include contact.php at the top. See below.
If you just plainly check if a $_POST variable is true, PHP will throw E_NOTICE errors. So best wrap the variable into the isset() (as in is this variable set) function. See below.
I refactored to prevent E_NOTICE errors and commented the changes.
contact.php
<?php
if (isset($_POST["submit"])) {
$error = [];
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!isset($_POST['name']) || strlen($_POST['name']) === 0) {
$error['name'] = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error['email'] = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST['message']) || strlen($_POST['name']) === 0) {
$error['message'] = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (empty($error)) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
index.php <-- Note the change of file extension
<?php include 'contact.php';?>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" method="post">
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Enter Your Name">
<?php if(isset($error['name'])) echo '<p class="text-danger">'.$error['name'].'</p>'; ?>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email">
<?php if(isset($error['email'])) echo '<p class="text-danger">'.$error['email'].'</p>'; ?>
</div>
<div class="form-group">
<textarea name="message" class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here"> </textarea>
<?php if(isset($error['message'])) echo '<p class="text-danger">'.$error['message'].'</p>'; ?>
</div>
<div class="form-group">
<input name="submit" type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text">SEND MESSAGE</input>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php if(isset($result)) echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
UPDATE
If you do not want a reload of the page when submitting the form, you will need some jQuery ajax action and alter your HTML and PHP file.
First remove the first line of your index.php that we added before:
<?php include 'contact.php';?><!-- Remove this one -->
You do not want the file to be included, but rather send data to it.
Next edit the HTML file and include jQuery library underneath your HTML (common practice to do JS stuff below HTML). Then alter your PHP file accordingly.
So your new HTML:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" name="contact" method="post">
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Enter Your Name" value="test">
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email" value="giroteam#localhost.com">
</div>
<div class="form-group">
<textarea name="message" class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here">test </textarea>
</div>
<div class="form-group">
<input name="submit" type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text" value="SEND MESSAGE">
</div>
<div class="form-group" id="result">
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ // launch when DOM is fully loaded
$('form[name="contact"]').submit(function(event){ // fire when you hit submit
event.preventDefault(); // prevent default form submission since you want to send data via ajax
$('#result').html('');
$('.alert').remove();
var values = $(this).serialize();
// Post form data to your contact.php script and work with response
$.ajax({
url: "contact.php",
type: "POST",
data: values ,
success: function (response) {
if(response.success) {
$('#result').html('<div class="alert alert-success">'+response.success+'</div>');
}
if(response.error_form) {
$.each( response.error_form, function( key, value ) {
$('input[name="'+key+'"]').parent().append('<p class="help-block text-danger">'+value+'</p>');
});
}
if(response.error_mail) {
$('#result').html('<div class="alert alert-danger">'+response.error_mail+'</div>');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
And finally the changed PHP:
<?php
ini_set('display_errors',0);
$result = [];
// Check if name has been entered
if (!isset($_POST['name']) || strlen($_POST['name']) === 0) {
$result['error_form']['name'] = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$result['error_form']['email'] = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST['message']) || strlen($_POST['message']) === 0) {
$result['error_form']['message'] = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (empty($result['error_form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if (mail ($to, $subject, $body, $from)) {
$result['success']='Thank You! I will be in touch';
} else {
$result['error_mail']='Sorry there was an error sending your message. Please try again later';
}
}
header('Content-type: application/json'); // tell browser what to expect
echo json_encode($result); // encode array to json object so javascript can work with it
I made such an elaborate example since many people decide to go ajax once they are successful in sending a regular form but notice that the page reloads ;)
I get what you want to achieve. You want to submit this form and if something is wrong, you want to show some error messages.
What has happened in your case is that, when you submit your form, it gets submitted to contact.php. Your browser will show what you return from the contact.php file. Since your contact.php do not include any HTML content and you don't write anything either, returned page doesn't include anything.
You have two options.
First way:
echo the error messages to the contact.php file. Add the following to the end of contact.php file.
echo $result;
This way, when someone submit your form. You will direct him to a new page which only have some line saying whether there was error or successful.
Second way
Move that logic to your index.html. You have to rename it to index.php. Then set the form to submit to the same page.
<form .... action="">
This will submit the form to the current page, which is index.php. Then, put your logic in contact.php at top of your index.php.

Contact PHP form - not receiving mail (GMAIL)

Ive been trying to get my contact form working, but i'm not receiving any emails in my gmail folders (including spam and trash. and also can't track anything through my host).
I've been following this tutorial: http://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
Need some serious help as i've tried everything!
<?php
$from = $_POST['email'];
$sendTo = 'myemail#gmail.com';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'email' => 'Email', 'phone' => 'Phone', 'message' => 'Message');
// array variable name => Text to appear in email
$okMessage = 'Contact form succesfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
THE HTML FORM
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div>
<div class="form-group">
<div class="row">
<div class="col-md-6 col-sm-12">
<label>First name*</label>
<input type="text" id="form-name" name="name" class="form- control" placeholder="Please enter your firstname *" required="required">
</div>
<div class="col-md-6 col-sm-12">
<label>Last name*</label>
<input type="text" name="surname" id="form-surname" class="form-control" placeholder="Please enter your firstname *" required="required">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6 col-sm-12">
<label>Email*</label>
<input type="email" name="email" id="form-email" class="form-control" placeholder="Please enter your firstname *" required="required">
</div>
<div class="col-md-6 col-sm-12">
<label>Phone</label>
<input type="tel" name="phone" id="form-phone" class="form- control" placeholder="Please enter your phone">
</div>
</div>
</div>
<div class="form-group">
<label for="comment">Message*</label>
<textarea class="form-control" rows="7" name="message" id="form-message" default="Type us a message" required="required"></textarea>
</div>
<div class="checkbox">
<label><input type="checkbox" value="">Join mailing list</label>
</div>
<input type="submit" class="btm btn-success btn-send" value="Send message">
<p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>
As many servers don't allow you to send emails in the name of someone whom is not registered, you should create an email on your server that's only for sending you the emails that your users write once they fill the contact form, then you should use a class like PHPMailer to send the email for you.
A simple example showing how to use PHPMailer would be:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.yourserver.here'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#userserver.here'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls';
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('user#userserver.here', 'Mailer');
$mail->addAddress('your#email.here', 'You'); // Add a recipient
$mail->addReplyTo('theuser#email.here', 'User that submitted form');
$mail->Subject = 'Subject here';
$mail->Body = 'Write here your message';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
The example is taken from the link I've told you above.
You don't have Mail Delivery error?
Try send email from know host in:
$from = $_POST['email']; (like youremail#gmail.com)
Gmail checks DKIM (posted by) and SPF (signed by) record in DNS server to email host. If email host don't have a DKIM record, email may be not supplied.
More (gmail):
https://support.google.com/mail/answer/180707?hl=en
More (How To Install and Configure DKIM):
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-dkim-with-postfix-on-debian-wheezy

Categories