So i managed to create an ajax form with jquery validation and I need to enchance it with php validation. Here is the code:
<!-- Contact form -->
<div id='contact_form_holder'>
<form action='index.php' method='post' id='contact_form'>
<p>
Your Name:
<div id='name_error' class='error'><img src='images/error.png'> Please enter your Name.</div>
<div><input class="textbox" type='text' name='name' id='name'></div>
</p>
<p>
Your Email:
<div id='email_error' class='error'><img src='images/error.png'> Please enter a valid Email.</div>
<div><input class="textbox" type='text' name='email' id='email'></div>
</p>
<p>
The Subject:
<div id='subject_error' class='error'><img src='images/error.png'> What is the purpose of the contact?</div>
<div><input class="textbox" type='text' name='subject' id='subject'></div>
</p>
<p>
The Message:
<div id='message_error' class='error'><img src='images/error.png'> Forgot why you came here?</div>
<div><textarea class="textbox" name='message' id='message'></textarea></div>
</p>
<div id='mail_success' class='success'><img src='images/success.png'> Your email has been submitted.Thank you.</div>
<div id='mail_fail' class='error'><img src='images/error.png'> There seems to be an internal error.Try later.</div>
<p id='cf_submit_p'>
<input class="button" type='submit' id='send_message' value='Send The Message'>
</p>
</form>
</div>
<!-- /Contact form -->
The send mail php code
$email_to = 'admin#localhost.com'; //the address to which the email will be sent
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
/*the $header variable is for the additional headers in the mail function,
we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
That way when we want to reply the email gmail(or yahoo or hotmail...) will know
who are we replying to. */
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
}else{
echo 'failed';// ... or this one to tell it that it wasn't sent
}
?>
And the jquery :
/// Contact Form ///
$(document).ready(function(){
$('#send_message').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
var re = new RegExp(/^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*#([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/);
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut.
The only difference from these checks is the email checking, we have
email.indexOf('#') which checks if there is # in the email input field.
This javascript function will return -1 if no occurence have been found.*/
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.lenght == 0 || !email.match(re)) {
var error = true;
$('#email_error').fadeIn(500);
} else {
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
}else{
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#cf_submit_p').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
$(':input','#contact_form')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
});
}
});
});
I have a very poor knowledge of php and I really need someone to help me validate this form with php if javascript is disabled and output the errors inside the correspoding error divs the jquery uses. Help would really be appreciated!
on index.php check values of your html fields
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if($_REQUEST['name']!="" && $_REQUEST['email']!="" && $_REQUEST['subject'] !="" && $_REQUEST['message']!="")
{
if (preg_match($regex, $_REQUEST['email'])) {
echo $email . \" is a valid email. We can accept it.\";
} else {
echo $email . \" is an invalid email. Please try again.\";
}
}
else{
echo "Error";
}
try to pass an error code to the page with the form via Redirection
http://example.com/form.php?error=1
and check the $_GET["error"] for the error code, display the message that is associated with the error where you want in the page
Related
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.";
}
?>
[I suspect the issue at hand has to do with how the php array gets passed to jQuery, if that isn't the case I apologize for the misleading title]
The contact form below is working -- except when I submit the forms' data, sometimes one field always keeps its red border indicating missing input, even when it actually has data.
To elaborate: I have a working php-only solution but on submit it causes a page-reload which I would like to avoid. After some research, it seems I need php/jQuery/ajax to perform these things asynchronously and to stay on the same site.
Desired behaviour:
So there are three required input fields called name, email and message, if any one is left out, it should receive a red border and no email gets sent.
Actual behaviour:
If for example only name and message are filled out and submitted, the empty email field is colored red.
But if a (valid) email is provided, the second submit action does not remove the red border around the email field.
I know that javascript and friends is a client-side language, and PHP gets processed server-side. Once the form is submitted, the .ajax function takes the serialized form values, uses 'POST' to stuff it into the php script and waits for the server to call us back inside .done()
This is where I'm lost - how is the php array to be used in jQuery?
E.g. no matter what, this line is never reached:
console.log("All fields filled and valid");
index.html:
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8" />
<script src="jquery-1.12.4.min.js"></script>
<script src="verify.js"></script>
<style>
.input-error
{
border: 2px solid red;
}
</style>
<script>
$(document).ready(function() // Wait until website (DOM) is completely loaded
{
/* Page top */
$('#pagetop').click(function()
{
console.log(this);
$('body, html').animate({scrollTop: '0px'}, 600);
return false;
});
});
</script>
</head>
<body>
<!-- action is left blank as process.php is called from verify.js -->
<form action="" method="POST" id="contactForm">
<label for="company">Company</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="company" name="company" value="">
<br><br>
<label for="name">Name *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="name" name="user_name" value="">
<br><br>
<label for="email">Email *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="email" name="user_email" value="">
<br><br>
<label for="message">Message *</label>
<br>
<textarea style="width: 904px; resize: none;" rows="9" id="message" name="user_message"></textarea>
<br><br>
<input type="submit" id="submit" name="submit" value="Send">
<br><br>
</form>
</body>
verify.js
$(document).ready(function()
{
// process the form
$('#contactForm').submit(function(event)
{
//$('#name, #email, #message').removeClass('input-error');
// process the form
$.ajax(
{
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : $('#contactForm').serialize(),
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data)
{
// log data to the console so we can see
console.log(data);
if (data.errors.name)
{
console.log("Name missing");
$('#name').addClass('input-error');
}
else
{
$('#name').removeClass('input-error');
}
// handle errors for email
if (data.errors.email)
{
console.log("Email missing or invalid");
$('#email').addClass('input-error');
}
else
{
$('#email').removeClass('input-error');
}
// handle errors for message
if (data.errors.message)
{
console.log("Message missing");
$('#message').addClass('input-error');
}
else
{
$('#message').removeClass('input-error');
}
if(data.input_valid == true)
{
console.log("All fields filled and valid");
alert('success');
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
process.php
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// Sanitize input variables
$company = test_input($_POST['company']);
$name = test_input($_POST['user_name']);
$email = test_input($_POST['user_email']);
$message = test_input($_POST['user_message']);
// Validate the variables
// If any of these variables don't exist, add an error to our $errors array
if (empty($name))
$errors['name'] = 'Name is required.';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL))
$errors['email'] = 'Valid Email is required.';
if (empty($message))
$errors['message'] = 'Message is required.';
$from = '--- Contact Form ---';
$to = 'some#mail.com';
$subject = 'Message from Contact Form';
$body = "From: $name\nCompany: $company\nE-Mail: $email\nMessage:\n\n$message";
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
if(mail($to, $subject, $body, $from))
{
$data['message'] = 'Thank you for your message!';
$data['mail_sent'] = true;
}
else
{
$data['message'] = 'Message could not be sent - please try again later.';
$data['mail_sent'] = false;
}
}
// return all our data to an AJAX call
echo json_encode($data);
// Convert special characters to html entities to prevent XSS attacks
// Also remove white-space and backslashes
function test_input($val)
{
$val = trim($val);
$val = stripslashes($val);
$val = htmlspecialchars($val);
return $val;
}
?>
It looks like if all validations pass in your php script, then data['errors'] is never defined. This might cause an error to be thrown (that you can see in the browser console) in the javascript when you write:
if (data.errors.name)
data.errors will evaluate to undefined in javascript, and when you try to access a property of undefined like data.errors.name, it will throw an error and stop the script.
To fix this, you probably just need to define errors in your php script, (though I'm not 100% sure the JSON methods won't leave out an empty array...). Try doing this in your php script:
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
$data['errors'] = $errors; // even though it is empty
// etc
EDIT:
I don't know if it will work with your jquery version but just in case it doesn't, place this code in your header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I used the below code and it worked. Sent the email without having to change the PHP code:
$(document).ready(function() {
$('#contactForm').submit(function(event) {
$.ajax({
type: 'POST',
url: 'process.php',
data: $('#contactForm').serialize(),
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
if(data.input_valid == true) {
console.log("All fields filled and valid");
// If the function is a success remove error classes from all fields
// you can either place the below code above the alert so that it happens
// before you get the success message, or after.
$('#name').removeClass('input-error');
$('#email').removeClass('input-error');
$('#message').removeClass('input-error');
alert('success');
} else {
if (data.errors.name) {
console.log("Name missing");
$('#name').addClass('input-error');
} else {
$('#name').removeClass('input-error');
}
if (data.errors.email) {
console.log("Email missing or invalid");
$('#email').addClass('input-error');
} else {
$('#email').removeClass('input-error');
}
if (data.errors.message) {
console.log("Message missing");
$('#message').addClass('input-error');
} else {
$('#message').removeClass('input-error');
}
}
});
event.preventDefault();
});
});
The contact form doesnt work
Here is the code im using in the page.
Jquery in Index.html
<!--contact form -->
<script type="text/javascript">
$(document).ready(function(){
$('#send_message').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut.
The only difference from these checks is the email checking, we have
email.indexOf('#') which checks if there is # in the email input field.
This javascript function will return -1 if no occurence have been found.*/
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#cf_submit_p').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
</script>
Here is the HTML Code for the Container
Contact-Form in HTML # index.html
<!--contact form -->
<div id="contact-form">
<div id="contact_form_holder">
<form action="index.php" method="post" id="contact_form">
<p>
Your Name:
<input name="name" class="field" id="name" type="text">
</p><div id="name_error" class="error"><img src="web_files/error.png"> Please enter your name</div>
<p></p>
<p>
Your Email:
</p><div><input name="email" class="field" id="email" type="text">
<div id="email_error" class="error"><img src="web_files/error.png"> OOps!! i can't get back to you in this mail id</div>
</div>
<p></p>
<p>
The Message:
</p><div>
<textarea name="message" class="field" id="message"></textarea>
<div id="message_error" class="error"><img src="web_files/error.png"> Forgot why you came here?</div></div>
<p></p>
<div id="mail_success" class="success"><img src="web_files/success.png"> Thank you. The mailman is on his way.</div>
<div id="mail_fail" class="error"><img src="web_files/error.png"> Sorry, don't know what happened. Try later.</div>
<p id="cf_submit_p">
<!--<input type='submit' id='send_message' value='Send it to me' class="submit"> -->
<input id="send_message" value="Send The Message" class="submit" type="submit">
</p>
</form>
</div>
</div>
<!--contact form -->
And at last here is the PHP code as
send_email.php
//we need to get our variables first
$email_to = 'mail#mail.com'<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l=document.getElementById("__cf_email__"); a=l.className;if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2) {c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s); l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
//the address to which the email will be sent
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*the $header variable is for the additional headers in the mail function,
we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
That way when we want to reply the email gmail(or yahoo or hotmail...) will know
who are we replying to. */
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
}else{
echo 'failed';// ... or this one to tell it that it wasn't sent
}
Your error is at your first line in your PHP-code:
$email_to = 'email#email.com'<script type="text/javascript">
Your string ends after the e-mail address. Correct it to
$email_to = 'email#email.com';
and you should be fine.
Also, what is the JavaScript doing inside the PHP? Remove it or make sure to either echo it, or place it outside of your PHP-tags.
1)Change the first line of your php code to
$email_to = 'some.person#example.com';
2)Remove the JavaScript from the PHP file.
If its still not working, change all the $_POST to $_GET and enter the values of the variables yourself. Then run the code and tell me the output.
EDIT :
I have found your error. You have not opened your php file correctly.
http://www.justyesh.in/send_email.php
You begin PHP with <?php and close it with ?>
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().
var text = $("input#text").val();
if (text == "") {
$("input#text").focus();
alert("Please complete all fields");
return false;
}
I have this jquery above to validate a textarea called "text". This, along with other values, get .ajax sent to a php page for sending an email. The email comes through fine with everything else in ok, but the textarea comes through as "undefined"? Any ideas? Do i need to post some more code?
EDIT:
Rest of the code:
the php:
$email = $_REQUEST['email'] ;
$text = $_REQUEST['text'] ;
$name = $_REQUEST['name'] ;
$detail = "Name: ".$name."\nMessage: ".$text;
mail( "xxxxxxxxx", "Subject: Contact Form",
$detail, "From: $email" );
echo "Thank you for getting in touch";
complete jquery:
$(function() {
$('#submit').live('click',function(){
var name = $("input#name").val();
if (name == "") {
$("input#name").focus();
alert("Please complete all fields");
return false;
}
var email = $("input#email").val();
if (email == "") {
$("input#email").focus();
alert("Please complete all fields");
return false;
}
var text = $("input#text").val();
if (text == "") {
$("input#text").focus();
alert("Please complete all fields");
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&text=' + text;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailform.php",
data: dataString,
success: function() {
alert("Thanks, we will be in touch soon");
}
});
return false;
});
});
The html:
<form method='post' action='mailform.php' class="form">
<p class="name">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</p>
<p class="email">
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
</p>
<p class="text">
<label for="text">Nature of Enquiry</label>
<textarea id="text" name="text"></textarea>
</p>
<p class="submit">
<input type="submit" id="submit" value="Send" />
</p>
</form>
I had a similar problem and my problem was with the php code. Try yo have a look there see if the #textarea gets _POST - ed correctly.
I am using this and works perfectly for me:
//we need to get our variables first
$email_to = 'xxxxx#yahoo.com'; //the address to which the email will be sent
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message']. "\n\n";
/*the $header variable is for the additional headers in the mail function,
we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
That way when we want to reply the email gmail(or yahoo or hotmail...) will know
who are we replying to. */
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
}else{
echo 'failed';// ... or this one to tell it that it wasn't sent
}
Not sure what's going on, like the other user said I believe to be a problem with the way the data is being carried over to the php script.
Try to look into $.post and serialize() functions that jquery can offer:
to give you an idea:
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
--- Due some checks to see if the info is correct---
if(error == false){
//#contact_form has all the variables that get serialized and sent to the php
and you can get a message back to check if everything went okay.
$.post("your_php_code.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#cf_submit_p').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});