How to integrate reCAPTCHA into existing php contact form? - php

I am trying to integrate a reCAPTCHA with my existing php contact form. Please can someone help? I have added the relevant code into the html form, I just don't know how to adapt my mailer.php code to perform the necessary backend checks and process the form data. I'm new to php and the code i have used I adapted from a site on the web. The form also uses ajax and query form validation.
<form id="form-ajax" class="form-ajax" method="post" action="mailer.php">
<input id="name" class="form-name" type="text" name="name" placeholder="Name" required>
<span class="error"></span>
<input id="email" class="form-email" type="email" name="email" placeholder="Email Address" required>
<span class="error"></span>
<textarea id="message" class="form-message" name="message" placeholder="Message..." required></textarea>
<span class="error"></span>
<div class="g-recaptcha" data-sitekey="my-site-key"></div>
<button class="form-submit" type="submit" name="submit">Send</button>
</form>
<script>
$(function() {
// Get the form
var form = $('#form-ajax');
// Get the messages div
var formMessages = $('#form-messages');
// Set up an event listener for the contact form
$(form).submit(function(event) {
// Stop the browser from submitting the form
event.preventDefault();
// Serialize the form data
var formData = $(form).serialize();
// Submit the form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text
$(formMessages).text(response);
// Clear the form
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
</script>
<?php
// Only process POST requests
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address
$recipient = "email#example.com";
// Set the email subject
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank you! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

Related

Submit form in React.js using Ajax

Creating my first application in React.js and want to submit contact form to a email with Ajax. I've used this solution as guideline: https://liusashmily.wordpress.com/author/liusashmily/ but the full component file is not available, only parts and I cant reach the author.
Contact component
// Create Component
class Contact extends React.Component {
constructor(props){
super(props);
this.state = {
contactEmail: '',
contactMessage: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleChangeMsg = this.handleChangeMsg.bind(this);
}
handleChange(event) {
this.setState({
contactEmail: event.target.value,
});
}
handleChangeMsg(event) {
this.setState({
contactMessage: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
this.setState({
type: 'info',
message: 'Sending…'
});
$.ajax({
url: 'php/mailer.php',
type: 'POST',
data: {
'form_email': this.state.contactEmail,
'form_msg': this.state.contactMessage
},
cache: false,
success: function(data) {
// Success..
this.setState({
type: 'success',
message: 'We have received your message and will get in touch shortly. Thanks!'
});
}.bind(this),
error: function(xhr, status, err) {
this.setState({
type: 'danger',
message: 'Sorry, there has been an error. Please try again later or visit us at SZB 438.'
});
}.bind(this)
});
}
render() {
return (
<div className="contact">
<form className="form" onSubmit={this.handleSubmit} id="formContact">
<label>Email</label>
<input id="formEmail" type="email" name="formEmail" value={this.state.contactEmail} onChange={this.handleChange} required />
<label>Meddelande</label>
<textarea id="formMsg" name="formMsg" rows="8" cols="40" value={this.state.contactMessage} onChange={this.handleChangeMsg} required></textarea>
<input type="submit" value="Submit" className="btn--cta" id="btn-submit" />
</form>
</div>
)
}
}
My PHP file mailer.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// $name = strip_tags(trim($_POST[“form_name”]));
// $name = str_replace(array(“\r”,”\n”),array(” “,” “),$name);
$email = filter_var(trim($_POST["formEmail"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["formMsg"]);
// Check that data was sent to the mailer.
if ( empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "mimilundberg#icloud.com";
// Set the email subject.
$subject = "New message from $email Via React Site";
// Build the email content.
$email_content .= "Email: $email\n\n";
$email_content .= "Message: \n$message\n";
// Build the email headers.
$email_headers = "From: <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn’t send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Getting following error in console log:
POST http://localhost:8080/php/mailer.php 404 (Not Found)
..and it says that error is in the "jquery-3.2.1.min.js:4" file.
I'm including jQuery script in html doc:
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<!-- <link rel="stylesheet" href="dist/styles.css"> -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div id="app"></div>
<script src="dist/bundle.js"></script>
</body>
</html>
So incredibly grateful for any input!
I found the solution. Here is my Contact component:
import React, { Component } from 'react';
// Contact component render contact form
class Contact extends React.Component {
constructor(props){
super(props);
this.state = {
contactEmail: '',
contactMessage: ''
};
this._handleSubmit = this._handleSubmit.bind(this);
this._handleChange = this._handleChange.bind(this);
this._handleChangeMsg = this._handleChangeMsg.bind(this);
}
// Change state of input field so text is updated while typing
_handleChange(e) {
this.setState({
contactEmail: e.target.value,
});
}
// Change state of input field so text is updated while typing
_handleChangeMsg(e) {
this.setState({
contactMessage: e.target.value
});
}
_handleSubmit(e) {
e.preventDefault();
this.setState({
contactEmail: '',
contactMessage: ''
});
$.ajax({
url: process.env.NODE_ENV !== "production" ? '/getMail' : "http://www.fransbernhard.se/magden/php/mailer.php",
type: 'POST',
data: {
'form_email': this.state.contactEmail,
'form_msg': this.state.contactMessage
},
cache: false,
success: function(data) {
// Success..
this.setState({
contactEmail: 'success',
contactMessage: '<h1>Kontakt skickad!</h1><p>Återkommer så fort som möjligt.</p>'
});
$('#formContact').slideUp();
$('#formContact').after(this.state.contactMessage);
console.log('success', data);
}.bind(this),
// Fail..
error: function(xhr, status, err) {
console.log(xhr, status);
console.log(err);
this.setState({
contactEmail: 'danger',
contactMessage: '<h1>Sorry det blev fel</h1><p>Försök gärna igen, eller mejla mig direkt på magdamargaretha#gmail.com</p>'
});
console.log(this.state.contactEmail + this.state.contactMessage + 'fail');
}.bind(this)
});
}
render() {
return (
<div className="contact" id="contact">
<div className="filter">
<form className="form" onSubmit={this._handleSubmit} id="formContact">
<label>Email</label>
<input id="formEmail" type="email" name="formEmail" value={this.state.contactEmail} onChange={this._handleChange} required/>
<label>Meddelande</label>
<textarea id="formMsg" name="formMsg" rows="8" cols="40" value={this.state.contactMessage} onChange={this._handleChangeMsg} required></textarea>
<input type="submit" value="Submit" className="btn--cta" id="btn-submit" />
</form>
</div>
</div>
)
}
}
export default Contact;
mailer.php file:
<?php
// trim() function strips any white space from beginning and end of the string
$email = filter_var(trim($_POST["form_email"]), FILTER_SANITIZE_EMAIL);
// strip_tags() function strips all HTML and PHP tags from a variable.
$message = strip_tags($_POST["form_msg"]);
// Check that data was sent to the mailer.
if ( empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "mimilundberg#icloud.com";
// Set the email subject.
$subject = "Message to magdalundberg.se from: $email";
// Build the email content.
$body .= "Email: $email\n\n";
$body .= "Message: \n$message\n";
// success
$success = mail($recipient, $subject, $body, "From:" . $email);
// Send the email.
if ($success) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn’t send your message.";
}
?>
As React is UI component framework you can use third party library for ajax post.
https://www.npmjs.com/package/react-axios
Here is an example of how to use this.
https://handyopinion.com/reactjs-post-form-with-ajax/

.php page loading when sending email from contact form (emails sending fine)

I'm not very good at php (yet) and my contact form somehow seems not to work properly when I hit send: my .php page appears with the message that should appear on top of the contact form itself (in the div called "form-letyouknow").
I have made contact forms using this code before with different ids so I am sure it's a very simple and stupid error but I've been over it so many times now that I need someone with fresh eyes to look.
Here is my code:
<div id="form-letyouknow">
<div id="form-messages"></div>
<form class="form" id="contact-form" method="post" action="send.php">
<div class="margin-bottom">
<label id="namelab" for="name">Nom:</br></label>
<input type="text" id="name" name="name" size="40" required>
</div>
<div class="margin-bottom">
<label for="email">Adresse e-mail:<br></label>
<input type="email" id="mail" name="email" size="40" required>
</div>
<div class="button" id="submit">
<label for="message" id="message-label">Message:<br></label>
<textarea id="msg" name="message" rows="8" cols="50" required></textarea>
</div>
<div class="field">
<button type="submit" id="send">Envoyer</button>
</div>
</form>
</div>
Jquery
$(function() {
// Get the form.
var form = $('#contact-form');
// Get the messages div.
var formMessages = $('#form-letyouknow');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
PHP
<?php
// POST requests.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! Il y a eu un problème. Avez-vous bien remplit tous les champs ?";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "my-email#email.com";
// Set the email subject.
$subject = "New message via website from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Send the email.
if (mail($recipient, $subject, $email_content)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Merci ! Votre message a été envoyé. J'y répondrai dans les plus brefs délais.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Une erreur est survenue. Vous pouvez m'envoyer un e-mail à l'adresse suivante: my-email#email.com";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "Une erreur est survenue lors de l'envoi de votre message. Réessayez ou envoyez moi un e-mail à l'adresse suivante: my-email#email.com";
}
?>
Thank you for taking the time and sorry if it's a dumb mistake.

Can't explain 400 bad request error from php/ajax form

I always get an unexplained 400 error when submitting an email through my form and i cannot understand why this is.
This worked on my local server, but when i uploaded it on the live website
Here is my HTML
<form method="post" id="ajax-contact" class="clearfix" action="js/mailer.php">
<input class="sb-search-input" placeholder="I want your freebies!" type="email" id="email" name="name" >
<input class="sb-search-submit" type="submit">
<button class="formbutton" type="submit">
<span class="fa fa-check"></span>
</button>
</form>
Here is my AJAX
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#email').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
Here is my PHP
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
echo "$email";
// Check that data was sent to the mailer.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "ahamdan#kindredbay.co.uk, aemmadi#kindredbay.co.uk";
// Set the email subject.
$subject = "New enquiry from $email";
// Build the email content.
$email_content .= "Email: $email\n\n";
// Build the email headers.
$email_headers = "From: $email <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Try replacing this in your form:
<input class="sb-search-input" placeholder="I want your freebies!" type="email" id="email" name="email" >

How to send confirmation email via PHP and Ajax?

I am working on a project with a simple PHP form with Ajax. The form sends email successfully but in AJAX messages it displays an error message that I have set: 'Oops! An error occured and your message could not be sent.
' could it be a server problem?
Also I want to send user a thank you (form submit confirmation) email after they submit the form on my website.
HTML Code:
<form id="ajax-contact" method="post" action="mailer.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Name" required name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="email" name="email" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="3" id="message" name="message"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
PHP mailer.php Code:
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "receiveremail#somewhere.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
AJAX Code:
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
just change this line and check once. even i had the same issue, i solved like this,
data: formData
to
data: {"postvalues":formData},
or
data: formData to data: {name: "sample",email:"your emal",message:"hi how are you"}
If you are using first one, make necessary changes in mailer.php. Like this
$post = $_POST['postvalues'];
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
If you follow second method, you cant serialize() form, and no need to change anything in mailer.php.
To send email to user who filled the form, use this
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
mail($email, "Contact Us", "Thank you for contacting us, we will get back to you soon", $email_headers)
}

Passing a variable from PHP to javascript and on to an html form

I'm having one, admittedly very minor issue with a contact form I've set up in WordPress using jQuery, jQuery form and PHP Mail to send a form-generated email.
To replace my current contact form which performs a pHp validation from within the contact form page and then sends using PHP Mail, I've designed the following simple html 5 form (which can be seen on this page: http://edge.donaldjenkins.net/contact):
<form id="contact" method="post" action="">
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" placeholder="Your Name" title="Enter your name" class="required">
<label for="email">E-mail</label>
<input type="email" name="email" placeholder="yourname#domain.com" title="Enter your e-mail address" class="required email">
<label for="phone">Phone</label>
<input type="tel" name="phone" placeholder="ex. (555) 555-5555">
<label for="website">Website</label>
<input type="url" name="url" placeholder="http://">
<label for="message">Question/Message</label>
<textarea name="message"></textarea>
<label for="checking" class="hidden">If you want to submit this form, do not enter anything in this field</label><input type="text" name="checking" class="hidden">
<input type="submit" name="submit" class="button" id="submit" value="Send Message" />
</fieldset>
I then use the jQuery validate [jquery.validate.js] and form [jquery.form.js] plugins to perform a client-end validation:
<script src="js/jquery.validate.js"></script>
<script src="js/jquery.form.js"></script>
<script>
$(function(){
$('#contact').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
url: 'send-message.php',
success: function() {
$('#contact').hide();
$('#instructions').hide();
$('#status').show();
$('#popular-posts').show();
$('#status').append("<p>Thanks! Your request has been sent. One will try to get back to you as soon as possible.</p>")
}
});
}
});
});
</script>
After the validation, the above script uses jQuery.form's ajaxSubmit function to submit the date to a server PHP page, send-message.php (the reason being that javascript can't send email). I use this PHP file to carry out a second, server-side validation of the data (though this is probably redundant, since because the setup relies on javascript to pass the data on to the server, one can safely assume that no one will be able to use the form without javascript enabled). It also performs a honeypot captcha check on data in a hidden input field added in the form. The email is then sent:
<?php
//invoke wp_load in order to use WordPress wp_mail plugin function instead of mail for better authentification of the sent email
require_once("/path/to/wp-load.php");
//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
$captchaError = true;
$errors .= "\n Error: Captcha field filled in";
} else {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) === '') {
$errors .= "\n Error: Name field empty";
$hasError = true;
} else {
$name = strip_tags($_POST['name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '') {
$emailError = 'You forgot to enter your email address.';
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$errors .= "\n Error: Message field empty";
$hasError = true;
} else {
$email = strip_tags($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) === '') {
$errors .= "\n Error: Message field empty";
$hasError = true;
} else {
$phone = strip_tags($_POST['phone']);
$url = strip_tags($_POST['url']);
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = strip_tags($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
// Send Message
$emailTo = 'me#mydomain.com';
$subject = 'Contact Form Submission from '.$name;
$body = "Name: $name \n\nEmail: $email \n\nPhone: $phone \n\nWebsite: $url \n\nMessage: $message";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$alert = 'Thanks! Your request has been sent. One will try to get back to you as soon as possible.';
} else {
$alert = $errors;
}
} ?>
The server keeps track of whether errors were found or whether the email was successfully sent in variable $alert.
After the pHp function completes, the script hides the form from the contact page and displays a previously hidden html element to which it appends an alert message.
The issue I can't solve is making javascript change the wording of that alert message to reflect whether the email was or not successfully sent, because I don't know how to pass the requisite pHp variable ($alert) containing a list of the error messages in the server PHP process to the script for insertion in the Contact Form page. Of course, again, this is a very theoretical concern, since for the reasons stated above, it's unlikely that an error-prone message would even have reached the PHP stage in the first place.
I've tried inserting the following code at the end of the PHP file, to no avail:
<script type="text/javascript">
alert = <?php echo $alert; ?>;
</script>
The latter attempt doesn't generate any errors in Firebug, but the variable value doesn't get passed on. Any ideas or thoughts welcome.
UPDATE: I added this workflow chart to clarify the setup for this issue:
In send-message.php, put the alert text in an IDd <div />:
<div id="statusmsg" style="display: none">
<?php echo $alert ?>
</div>
Then your Javascript on the calling page ought to look like this:
<script type="text/javascript">
$(function() {
$('#contact').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
url: 'send-message.php',
success: function(data) {
$('#contact').hide();
$('#instructions').hide();
$('#status').show();
$('#popular-posts').show();
// Make DOM object from result
var $DOMObj = $(data);
// Retrieve status message, if any
var $status = $('#statusmsg', $DOMObj);
// Show status message, if any
if ($status) {
$status
.css('display', '')
.appendTo('#status');
}
}
});
}
});
});
</script>
Hopefully you can see how I've used a parameter to the success callback to retrieve the HTML contents of the AJAX request response, located the statusmsg div and appended it to the relevant element on the calling page.
More optimally, send-message.php would print JSON rather than HTML, making this process a little easier. I'll leave that as an exercise for the reader.. at least in this question thread.
You want to return the success or failure of the email in response to the AJAX call.
For this sample example, you could simply return false or true. If you needed more information, return a JSON string such as...
{
"success": true,
"something": ["something", "something-else"]
}
You can easily turn an array into JSON in PHP with json_encode().

Categories