I am new to programming and after a zillion hours working on this I am not getting any closer to a solution. Any help would be greatly appreciated.
I have a form that I am sending to php via ajax(although I don't see /process.php in the address bar after the domain name, or does that even matter?). The confirmation from php does load on the page but the email with the form values does not get sent. I work very hard at this, and I really do believe I'll get this stuff, but right now I am in need a little help. A live version can be viewed at http://www.hydrodyneh2o.com.
Thanks in advance.
$(document).ready(function(){
//Script for "Submit" button to submit and load 'submission confirmation'
$('#hydrodyne-form input[type="submit"]').click(function(e){
e.preventDefault();
//alert("never!");
$('#hydrodyne-form .warn').remove();
var fields = $('#hydrodyne-form').serializeArray();
$.ajax({
type : 'POST',
url : 'processForm.php',
data : fields,
dataType : 'json',
success: function(data) {
if (data.error) {
$.each(data.fields, function(k, v) {
$('.' + k).append('<span class="warn">' + v + '</span>');
$('.warn').fadeIn(700);
});
} else {
$('#form-content').fadeOut(700, function() {
$(this).hide();
$('#form-content').addClass('processing').html('Processing...').fadeIn(400);
$('#form-content').delay(1300).fadeOut(700).hide(function(){
$(this).removeClass('processing').html(data.confirm).fadeIn(400);
});
});
}
},
error: function(data) {
$('#form-content').hide().html('<p id="error" class="italic inside-text">*Error occurred</p>').fadeIn(700);
}
});
return false;
});
});
PHP (processForm.php):
<?php
$service = $_POST['service'];
$service_type = implode(",\r\n• ",$service);
if ($_POST) {
$expected_inputs = array('company', 'contact_name', 'phone_number', 'email');
$validation = array(
'company' => 'Company Name Required',
'contact_name' => 'Contact Name Required',
'phone_number' => 'Phone Number Required',
'email' => 'Email Address Required'
);
$company = stripslashes($_POST['company']);
$contact_name = stripslashes($_POST['contact_name']);
$phone_number = stripslashes($_POST['phone_number']);
$email = stripslashes($_POST['email']);
$project_summary = stripslashes($_POST['project_summary']);
$to = 'brian#bseifert.com';
$subject = 'You\'ve got a Website Inquiry!';
$message = "\r\n Contact Name: " . $contact_name .
$message = "\r\n\r\n Company: " . $company .
$message = "\r\n\r\n Phone Number: " . $phone_number .
$message = "\r\n\r\n Email Address: " . $email .
$message = "\r\n\r\n\r\n Type of Anticipated Service: \r\n\r\n " . $service_type .
$message = "\r\n\r\n\r\n Message: \r\n\r\n" . $project_summary;
$message = wordwrap($message, 80);
$errors = array();
$output = array();
foreach($expected_inputs as $key) {
if (array_key_exists($key, $_POST)) {
if (empty($_POST[$key])) {
$errors[$key] = $validation[$key];
} else {
$output[$key] = $_POST[$key];
}
} else {
$errors[$key] = $validation[$key];
}
}
if (!empty($errors)) {
$array = array('error' => true, 'fields' => $errors);
} else {
// PROCESS FORM
mail($to, $subject, $message) or die('not working!!!');
$confirm =
'<div id="logo" style="margin:80px 0 0 335px;"></div>
<img class="absolute" style="top:158px; left:265px;" src="IMG/inside-pgs/checkmark.png" alt="" />
<div class="inside-text thank-you">
<p>Your message has been sent.<br/> A representative from Hydrodyne will contact you<br/> as soon as possible.</p>
</div>';
$array = array('error' => false, 'confirm' => $confirm);
}
echo json_encode($array);
}
?>
HTML:
<div id="form-content">
<div id="inside-pg-heading">
<img src="IMG/inside-pgs/contact.gif" alt=""/>
</div><!-- end inside-pg-heading -->
<img class="hydroArrowContact absolute" src="IMG/inside-pgs/hydroArrowContact.png" alt="" />
<p class="hydroArrowContactText absolute">ydrodyne thanks you for stopping by, and asks that you use the form below <br>to ask any questions or place a request. We look forward to hearing from you!</p>
<div class="absolute" style="width:950px; top:132px; left:35px;">
<!-- <div id="response"></div> -->
<form id="hydrodyne-form" action="processForm.php" method="post">
<div id="formCol1">
<h5 class="form-heading inside-text bold italic"><span style="font-size:14px;">Fields marked with an asterisk (*) are required.</span></h5>
<div id="text-inputs" class="inside-text bold italic">
<div id="inputCol1">
<h4 class="company">* Company</h4>
<input type="text" name="company"<br/>
<h4 class="contact_name">* Contact Name</h4>
<input type="text" name="contact_name"<br/>
</div><!-- end inputCol1 -->
<div id="inputCol2">
<h4 class="phone_number">* Phone Number</h4>
<input type="text" name="phone_number"<br/>
<h4 class="email">* Email Address</h4>
<input type="text" name="email"<br/>
</div><!-- end inputCol2 -->
</div><!-- end text-inputs -->
<div class="clear"></div>
<h4 class="form-heading inside-text bold italic">Please check anticipated service(s)</h4>
<div class="checkboxes green">
<div id="checkboxCol1">
<input type="checkbox" name="service[]" value="Wastewater Flushing / Laundry"> Wastewater Flushing / Laundry<br/>
<input type="checkbox" name="service[]" value="Irrigation"> Irrigation<br/>
<input type="checkbox" name="service[]" value="Vehicle Washing"> Vehicle Washing<br/>
<input type="checkbox" name="service[]" value="Animal Feeding"> Animal Feeding
</div><!-- end checkboxCol1 -->
<div id="checkboxCol2">
<input type="checkbox" name="service[]" value="Commercial / Industrial Cooling"> Commercial / Industrial Cooling<br/>
<input type="checkbox" name="service[]" value="Commercial / Industrial Processing"> Commercial / Industrial Processing<br/>
<input type="checkbox" name="service[]" value="Fire Suppression"> Fire Suppression
</div><!-- end checkboxCol2 -->
</div><!-- end checkboxes -->
</div><!-- end formCol1 -->
<div id="formCol2">
<h5 class="form-heading inside-text bold italic">Provide Hydrodyne with more information by typing a brief message in the box below.</h5>
<textarea name="project_summary"></textarea>
<input type="submit" value="">
</div><!-- formCol2 -->
</form>
</div>
</div><!-- end form-content -->
According to the pHp documentation: http://php.net/manual/en/function.mail.php#example-3381
you can add a header to the mail();
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// PROCESS FORM
mail($to, $subject, $message, $headers) or die('not working!!!');
Also you should check the following line as I guess there is a invalid character which can create any unwanted pHp Warnings/errors;
$service_type = implode(",\r\n• ",$service);
it should be:
$service_type = implode(",\r\n",$service);
Thank you Nouphal.M! Man, I spent a lot of time searching for a solution when all I needed to do was check my spam. I really appreciate your time and efforts everyone!
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 2 years ago.
I am in the process of creating a website for my company, I don't have a lot of money but a lot of time. I bought my domain names, my web host etc.
in short in the site that I create I want to integrate a contact form with JS AJAX PHP on an html website. I specify that I also use BULMA for formatting. it's kind of like Bootstrap. I show you what I did.
email does not send to address. i dont know how to add imap or smtp. can you help me solve my problem please?;
my .html file named index.html :
<!-- body -->
<body>
<!-- contact -->
<div class="block">
<footer class="footer">
<h2 class="heading-site">Contactez-moi</h2>
<div class="footer-contact-form">
<form>
<div class="field">
<label class="label">Votre nom</label>
<div class="control">
<input id="name" class="input" type="text" placeholder="votre prénom" name="name">
</div>
</div>
<div class="field">
<label class="label">Votre Prénom</label>
<div class="control">
<input id="firstname" class="input" type="text" placeholder="votre nom" name="firstname">
</div>
</div>
<div class="field">
<label class="label">Votre email</label>
<div class="control">
<input id="email" class="input" type="text" placeholder="votre-email#mail.fr" name="email">
</div>
</div>
<div class="field">
<label class="label">Votre message</label>
<div class="control">
<textarea id="message" class="textarea" placeholder="Décrivez votre entreprise et expliquez en quoi puis-je vous aider" name="message"></textarea>
</div>
</div>
</form>
<button class="button is-link" id="send_email">Envoyer !</button>
</div>
<div class="footer-informations">
<p>65 rue des peupliers</p>
<p>75015 Paris</p>
<ul>
<li>
<a href="#">
<i class="fab fa-facebook-square"></i>
</a>
</li>
<li>
<a href="#">
<i class="fab fa-twitter-square"></i>
</a>
</li>
</ul>
</div>
</footer>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="src/js/main.js"></script>
</body>
<!-- body -->
my .js file named main.js :
// send mail with ajax
$('#send_email').click(function(e){
e.preventDefault();
var data = {
email: $('#email').val(),
name: $('#name').val(),
firstname: $('#firstname').val(),
message: $('#message').val()
};
// AJAX
$.ajax({
url: "mail.php",
type: 'POST',
data: data,
success: function(data) {
$('#js_alert_success').css({'display' : 'block'});
setTimeout(function(){
$('#js_alert_success').css({'display' : 'none'});
$('#email').val("");
$('#name').val("");
$('#firstname').val("");
$('#message').val("")
}, 3000);
},
error: function(data) {
$('#js_alert_danger').css({'display' : 'block'});
setTimeout(function(){
$('#js_alert_danger').css({'display' : 'none'});
$('#email').val("");
$('#name').val("");
$('#firstname').val("");
$('#message').val("")
}, 3000);
}
});
});
my php file who named mail.php :
<?php
if($_POST){
$firstname = $_POST['firstname']
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: $name <$email>\r\nReply-to : $name <$email>\nX-Mailer:PHP";
$subject="demande de renseignement";
$destinataire="j.dalverny#collaborateur-architecte.com";
$body="$message";
if(mail($destinataire,$subject,$body,$headers)) {
$response['status'] = 'success';
$response['msg'] = 'your mail is sent';
} else {
$response['status'] = 'error';
$response['msg'] = 'Something went wrong';
}
echo json_encode($response);
}
?>
I
Please follow the below example of mail sending and let me know if you have issue understanding any part of it
PHP section
require_once "Mail.php"; // PEAR Mail package
require_once ('Mail/mime.php'); // PEAR Mail_Mime packge
$name = $_POST['name']; // form field
$email = $_POST['email']; // form field
$message = $_POST['message']; // form field
if ($_POST['submit']){
$from = "myemail#mydomain.com"; //enter your email address
$to = "john#myfriendsdomain.com"; //enter the email address of the contact your sending to
$subject = "Contact Form"; // subject of your email
$headers = array ('From' => $from,'To' => $to, 'Subject' => $subject);
$text = ''; // text versions of email.
$html = "<html><body>Name: $name <br> Email: $email <br>Message: $message <br></body></html>"; // html versions of email.
$crlf = "\n";
$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
//do not ever try to call these lines in reverse order
$body = $mime->get();
$headers = $mime->headers($headers);
$host = "localhost"; // all scripts must use localhost
$username = "myemail#mydomain.com"; // your email address (same as webmail username)
$password = "23ert5"; // your password (same as webmail password)
$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true,
'username' => $username,'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
}
else {
echo("<p>Message successfully sent!</p>");
}
}
HTML Section
<form action="qservers_mail.php" method="post">
<table border="0" style="background:#ececec" cellspacing="5">
<tr align="left"><td>Name</td><td><input type="text" size="30" name="name"></td></tr>
<tr align="left"><td>Email address</td><td><input type="text" size="30" name="email"></td></tr>
<tr align="left"><td valign="top">Comments</td><td><textarea name="message" rows="6" cols="30"></textarea></td></tr>
<tr align="left"><td> </td><td><input type="submit" value="Send" name='submit'></td></tr>
</table>
</form>
I was mistaken that I was missing anything from my PHP file. The only thing which makes the contact form working is if I use a way older version of the jQuery but that cannot be the case because I need SSL on my site and Google determines the site unsafe which wants to load unsafe scripts if they are older.
Here is the old version of the scripts:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
window.jQuery || document.write('</script>')
<script type="text/javascript" src="js/jquery-migrate-1.2.1.min.js"></script>
And here is what I was trying to use. I downloaded js files and uploaded to the server but I thinks because of the many function changes my PHP file cannot do the work anymore.
Can somebody help me to update my PHP file because I don't really do coding :o. Tried to understand how it works however I got confused.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-3.3.1.min.js"><\/script>')</script>
<script type="text/javascript" src="js/jquery-migrate-3.0.0.min.js"></script>
I use a template from Styleshout called Kreative101 and modified it in many ways but I didn't touch the contact form nor the PHP file (only inserting the error reporting and the email address).
I don't know if it needs any jQuery script in order to work because I did change that and the Modal Popup stopped working. Now it is back to the original (at least the footer with the scripts). The modal works the contact form doesn't.
Any help will be highly appreciated;).
If a reload the page says the action I took will be repeated
The contact form worked before, I tested it.
Here is the HTML code
<section id="contact">
<div class="row section-head">
<div class="col full">
<h2>Contact</h2>
<p class="desc">Get in touch with us</p>
</div>
</div>
<div class="row">
<div class="col g-7">
<!-- form -->
<form name="contactForm" id="contactForm" method="post" action="">
<fieldset>
<div>
<label for="contactName">Name <span class="required">*</span></label>
<input name="contactName" type="text" id="contactName" size="35" value="" />
</div>
<div>
<label for="contactEmail">Email <span class="required">*</span></label>
<input name="contactEmail" type="text" id="contactEmail" size="35" value="" />
</div>
<div>
<label for="contactSubject">Subject</label>
<input name="contactSubject" type="text" id="contactSubject" size="35" value="" />
</div>
<div>
<label for="contactMessage">Message <span class="required">*</span></label>
<textarea name="contactMessage" id="contactMessage" rows="15" cols="50" ></textarea>
</div>
<div>
<button class="submit">Submit</button>
<span id="image-loader">
<img src="images/loader.gif" alt="" />
</span>
</div>
</fieldset>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="icon-ok"></i>Your message was sent, thank you!<br />
</div>
</div>
And the PHP code (I inserted the error reporting but I don't know if it's correct.)
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
// Replace this with your own email address
$siteOwnersEmail = 'info#virtualpropertyreview.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
In the comment I suggested to redirect after sending the mail - not sure if you understood what I meant but like this.
$mail = mail( $siteOwnersEmail, $subject, $message, $headers );
header('Location: ?mailsent=' . $mail ? 'true' : 'error' );
That should prevent the form being submitted if the page is reloaded accidentally etc
You could use that GET variable to display a message to report on status of the mail send.
if( !empty( $_GET['mailsent'] ) ){
echo $_GET['mailsent']=='true' ? "your message was sent" : "Sorry, there was an error"; /* etc */
}
I am building a website that has a form that when the submit button is selected it is supposed to send an automated email. I have been able to get the HTML portion of the form to send properly. The verification also works. The issue is no physical email is being sent. How should I error test this?
The form is built in Visual Studio using html. Here is the code for the form
<div class="one_half">
<form action="demo-contact.php method="post" id="sky-form" class="sky-form">
<h2 class="uppercase"><strong>Contact Form</strong></h2>
<fieldset>
<div class="row">
<section class="col col-6">
<label class="label">Name</label>
<label class="input"> <i class="icon-append icon-user"></i>
<input type="text" name="name" id="name">
</label>
</section>
<section class="col col-6">
<label class="label">E-mail</label>
<label class="input"> <i class="icon-append icon-envelope-alt"></i>
<input type="email" name="email" id="email">
</label>
</section>
</div>
<section>
<label class="label">Subject</label>
<label class="input"> <i class="icon-append icon-tag"></i>
<input type="text" name="subject" id="subject">
</label>
</section>
<section>
<label class="label">Message</label>
<label class="textarea"> <i class="icon-append icon-comment"></i>
<textarea rows="4" name="message" id="message"></textarea>
</label>
</section>
<section>
<label class="checkbox">
<input type="checkbox" name="copy" id="copy">
<i></i>Send a copy to my e-mail address</label>
</section>
</fieldset>
<footer>
<button type="submit" class="button">Send message</button>
</footer>
<div class="message"> <i class="icon-ok"></i>
<p>Your message was successfully sent!</p>
</div>
</form>
</div>
Additonally there is a error check in
$(function()
{
// Validation
$("#sky-form").validate(
{
// Rules for form validation
rules:
{
name:
{
required: true
},
email:
{
required: true,
email: true
},
message:
{
required: true,
minlength: 10
}
},
// Messages for form validation
messages:
{
name:
{
required: 'Please enter your name',
},
email:
{
required: 'Please enter your email address',
email: 'Please enter a VALID email address'
},
message:
{
required: 'Please enter your message'
}
},
// Ajax form submition
submitHandler: function(form)
{
$(form).ajaxSubmit(
{
success: function()
{
$("#sky-form").addClass('submited');
}
});
},
// Do not change code below
errorPlacement: function(error, element)
{
error.insertAfter(element.parent());
}
});
});
The issue I am experiencing is with the php code.
<?php
if( isset($_POST['name']) )
{
$from = "Sender <postmaster#skyvantagemedia.com>";
$to = "Recipient <skyvantage#outlook.com>";
$subject = $_POST['subject'];
$message = $_POST['message'] . "\n\n" . 'Regards, ' . $_POST['name'] . '.';
$host = "mail.skyvantagemedia.com";
//IMPORtANT: This email MUST be same as your FROM address.
$username = "postmaster#skyvantagemedia.com"; //IMPORtANT: This email MUST be same as your FROM address.
//IMPORtANT: This email MUST be same as your FROM address.
$password = "*********";
$headers = 'From: ' . $_POST['name'] . "\r\n" . 'Reply-To: ' . $_POST['email'] . "\r\n" . 'X-Mailer: PHP/' . phpversion();
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
}
?>
Currently the HTML works but no email is being sent. Any advice on how to error trap the problem would be appreciated.
I am not sure if this will help or work, but here is the default/original PHP that comes with SkyPro.
<?php
session_start();
if( isset($_POST['name']) && strtoupper($_POST['captcha']) == $_SESSION['captcha_id'] )
{
$to = 'example#someEmail.com'; // Replace with your email
$subject = 'Message from website'; // Replace with your $subject
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Name: ' . $_POST['name'] . "\n" .
'E-mail: ' . $_POST['email'] . "\n" .
'Subject: ' . $_POST['subject'] . "\n" .
'Message: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
}
?>
Maybe try replacing yours with back to the original and give it a shot. Cheers!
I have a pretty basic PHP site and I want a simple spam protection to stop the spam submissions.
I've found one that I like which is a basic 4 character input. Easy to read, small space requirements.
But it says to use a validate.php for the submission action.
My current form's action is to call a the mailer.php (<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">) which is actually included on page load (<?php include 'includes/mailer.php'; ?>).
Can I have two 'actions'? If not, how can I implement the use of this captcha?
When I try adding session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
Just after the opening <?php in mailer.php and then }
else
{
die("Wrong Code Entered");
} just before the closing ?>, the whole website just displays "Wrong code entered" on load.
EDIT:
I'm having trouble understanding where I need to place the various parts of the code and how to tweak it so it works with the existing mailer script.
My unmodified index.php basically consists of the following:
<?php
include 'includes/mailer.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section id="section-home">
<header>
<!-- header content -->
<!-- navigation -->
</header>
</section>
<section class="banner full-width-container">
<div class="container">
<!-- other body content -->
<div id="contact">
<div id="contact-form-message"><?php print $output; ?></div>
<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">
<p><span style="color:#f7403a;">Fill in the form below to have an expert contact you</span></p>
<div class="form-left">
<div class="control-group">
<label for="name" class="assistive control-label">Name:</label>
<div class="controls">
<input type="text" name="name" id="name" value="Your Name" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="email" class="assistive control-label">Email: </label>
<div class="controls">
<input type="text" name="email" id="email" value="Your email address" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-left -->
<div class="form-right">
<div class="control-group">
<label for="subject" class="assistive control-label">Subject: </label>
<div class="controls">
<input type="text" name="subject" id="subject" value="Subject" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="telephone" class="assistive control-label">Telephone number </label>
<div class="controls">
<input type="text" name="telephone" id="telephone" value="Your phone number" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-right -->
<div class="control-group">
<label for="message" class="assistive control-label">Message: </label>
<div class="controls">
<textarea name="message" id="message" class="replace-default required type-textarea full-width" rows="5" cols="20">The type of enquiry (e.g. Motor Accident) and a brief message</textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" id="submit" name="submit" class="btn btn-stacks" value="Send Message"/>
<div id="sending-message"><img src="img/ajax-loader.gif" alt="" /></div>
</div>
</div>
</form>
</div>
</div>
</section>
<footer class="full-width-container" id="footer-section">
<div class="container">
<!-- footer content -->
</div>
</footer>
<!-- ============================================== -->
<script src="js/modernizr-1.7.min.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.flexslider-min.js"></script>
<script src="js/waypoints.min.js"></script>
<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
And my unmodified mailer.php consist of:
<?php
function cleanInput($input){
$input = trim($input);
if(strlen($input)>0){
$input = htmlspecialchars(stripslashes($input));
}
return $input;
}
$name = '';
$email = '';
$subject = '';
$message = '';
$telephone = '';
$output = '';
if ( isset($_POST['submit']) || isset($_GET['ajax']) == 'true'){
//set up for form fields
$name = cleanInput($_POST['name']);
$email = cleanInput($_POST['email']);
$subject = cleanInput($_POST['subject']);
$telephone = cleanInput($_POST['telephone']);
$message = cleanInput($_POST['message']);
$output ='';
$regex = "/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$/ix";
//do some basic validation
if( $name == '' || $name == 'Full Name' ){ $output = '<li class="alert alert-error">Please enter your name.</li>'; }
if ( !preg_match( $regex, $email ) || $email == 'Email address' ) {
$output .= '<li class="alert alert-error">Please check that your email address is valid</li>';
}
if( $subject == '' || $subject == 'Subject' ){ $output .= '<li class="alert alert-error">Please enter a subject</li>'; }
if( $telephone == '' || $telephone == 'Contact number' ){ $output .= '<li class="alert alert-error">Please enter a contact number</li>'; }
if( $message == '' || $message == 'Your Query' ){ $output .= '<li class="alert alert-error">Please enter a message</li>'; }
//if there are errors, add them to the list here
if ( $output!='' ){
$output = '<div class=""><ul class="unstyled">' . $output . '</ul></div>';
}
//if no errors, try to send the form
else {
/*Put the email address to send to here*/
$to = "email1#domain.com.au";
$headers = 'From: noreply#domain.com.au' . "\r\n";
$headers .= 'Cc: '. $email . "\r\n";
$headers .= 'Bcc: email2#domain.com.au' . ', ' . 'email3#domain.com.au' . ', ' . 'email4#otherdomain.com.au' . "\r\n";
$subject = $subject;
$body = "Name: $name\n\n"
. "Email: $email\n\n"
. "Subject: $subject\n\n"
. "Message: $message"
;
$messageOK = ( mail($to, 'Web Enquiry from the landing page for: ' . $subject, $body, $headers ));
//check if the mail was sent or not
if ( $messageOK ){
$output = '<div class="alert alert-success"><p>Thank you for getting in touch. We will be in contact soon.</p></div>';
}
else {
$output = '<div class="alert alert-error"><p>We could not send your message. Please try again.</p></div>';
}
}
//if ajax is being used, output the message
if ( isset($_GET['ajax']) == 'true' ){
print $output;
}
}
?>
Any information that helps me understand what is required to use this captcha code would be greatly appreciated
You could use a random number generated when form is generated, then passing the value using POST AND $_SESSION, and then compare 2 to see if they match. This is for bot protection/spam.
Would you like an example?
EDIT, didn't fully read the question.
What you want to do is to decide whether the page is loaded as POST request, if is not, then display the form, if is, validate $_POST fields and/or send email.
session_start();
$error = null;
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff`
else
{
$error = "invalid captcha image, please try again!";
}
//the rest of your HTML
//after the recaptcha image HTML
echo isset($error)? $error: '';
This will stop the page from dieing because of the failed captcha, and will produe an error message of 'Invalid captcha image' if the capthc was false.
I have a contact form that passes the data via jQuery $.post.
JS
$(function () {
$("#contact_form").submit(function (a) {
a.preventDefault();
$.post("<?php echo home_url('/_asset/contact.php'); ?>", {
contact_name : $("#contact_name").val(),
contact_email : $("#contact_email").val(),
contact_subject : $("input:radio[name=subject]:checked").val(),
contact_textarea: $("#contact_textarea").val(),
contact_postid : $("#contact_postid").val(),
}, function (a) {
$("div#response").removeClass("hidden");
$("div#response").delay(1E3).html(a);
});
});
});
contact.php
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_subject = $_POST['contact_subject'];
$contact_message = $_POST["contact_textarea"];
$contact_postid = $_POST['contact_postid'];
$contact_address = $_SERVER['REMOTE_ADDR'];
if( empty($contact_name) && empty($contact_email) && empty($contact_subject) && empty($contact_message) ) {
die('You must fill out all fields amigo!');
}
// Build that email boy!
if( !empty($contact_postid) ) { $email_id = ' (' . $contact_postid . ')'; }
$email_to = 'email#example.com';
$email_subject = 'Contact Form: ' . $contact_subject . $email_id;
$email_header = 'From: ' . $contact_name . '<' . $contact_email . '>' . "\r\n";
$email_header .= 'Reply-To:' . $contact_email . "\r\n";
$email_header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$email_message = nl2br($contact_message);
// Try sending the email
if(!mail($email_to, $email_subject, $email_message, $email_header)){
$status = 'red';
die('Error sending email.');
} else {
$status = 'green';
die('Email sent!');
}
PHP form
<div class="respond_form">
<form method="post" id="contact_form">
<h2>Let's get contacting!</h2>
<div id="response" class="hidden alert <?php echo $status; ?>"></div>
<div class="line">
<label for="contact_name" title="Please enter your name (required)">Your name <span class="required">*</span></label>
<input type="text" name="contact_name" id="contact_name" tabindex="1" placeholder="John Smith" required="required"/>
</div>
<div class="line">
<label for="contact_email" title="Please enter your email (required)">Your email (so we can contact you) <span class="required">*</span></label>
<input type="email" name="contact_email" id="contact_email" tabindex="2" placeholder="mail#example.com" required="required"/>
</div>
<?php if( isset($_GET['subject']) ) { ?>
<input hidden="hidden" name="subject" type="radio" value="<?php echo $_GET['subject']; ?>" checked="checked">
<?php if( isset($_GET['PostID']) ) { echo '<input hidden="hidden" id="contact_postid" name="postid" type="input" value="' . $_GET['PostID'] . '">'; } ?>
<?php } else { ?>
<div class="line">
<label>What is the message in regards to? <span class="required">*</span></label>
<ul style="list-style:none; margin: 0; padding: 0;">
<label style="font-weight:normal;"><input style="margin-right: 10px;" name="subject" type="radio" value="Advertising"<?php if( $_GET['subject'] == 'advertising' ) { echo ' checked="checked"'; } ?>>Advertising</label>
<label style="font-weight:normal;"><input style="margin-right: 10px;" name="subject" type="radio" value="Contribute an Article"<?php if( $_GET['subject'] == 'contribute' ) { echo ' checked="checked"'; } ?>>Contribute an Article</label>
</ul>
</div>
<?php } ?>
<div class="line">
<label for="contact_textarea" title="Briefly explain your message (required)">Briefly explain your message <span class="required">*</span></label>
<textarea name="contact_textarea" id="contact_textarea" rows="10" tabindex="3" maxlength="500" required="required"></textarea>
</div>
<input type="submit" id="contact_send" name="contact_send" class="button glow" value="Send Message"/>
</form>
</div>
As you can see, I've tried setting a $status in the mail() function but that didn't work. I'm not entirely sure what's going on with the whole thing (found it ages ago and just built around it) but I know the die() message emits into the div#response.
Effectively I was hoping to add a class to the div#response if the email was successful or not.
OH! and incase someone wants to comment on the lack of security, or checking of $_POST data, I've stripped it for here :]
$.post sends the data to contact.php and loads its response.
In your case, the response is text that can be "Error sending email." or "Email sent!" (from what you posted) so you just need to test the value and add the related class.
$(function () {
$("#contact_form").submit(function (a) {
a.preventDefault();
$.post("<?php echo home_url('/_asset/contact.php'); ?>", {
contact_name : $("#contact_name").val(),
contact_email : $("#contact_email").val(),
contact_subject : $("input:radio[name=subject]:checked").val(),
contact_textarea: $("#contact_textarea").val(),
contact_postid : $("#contact_postid").val(),
}, function (a) {
$("div#response").removeClass("hidden").addClass( (a=="Email sent!") ? "email-success" : "email-error" );
$("div#response").delay(1E3).html(a);
});
});
});