Here is the code I'm using for the submitHandler:
submitHandler: function() {
$('.holder').fadeOut('slow');
$('#loading').fadeIn('slow');
$.post('email.php',{name:$('#em_name').val(), email:$('#em_email').val(), message:$('#em_message').val()},
function(data){
$('#loading').css({display:'none'});
if( data == 'success') {
$('#callback').show().append('Message delivered successfully');
$('#emailform').slideUp('slow');
} else {
$('#callback').show().append('Sorry but your message could not be sent, try again later');
}
});
}
This isn't working when used in conjunction with this php:
<?php $name = stripcslashes($_POST['name']);
$emailAddr = stripcslashes($_POST['email']);
$message = stripcslashes($_POST['message']);
$email = "Message: $message \r \n From: $name \r \n Reply to: $emailAddr";
$to = 'mail#example.com';
$subject = 'Message from example';
//validate the email address on the server side
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $emailAddr) ) {
//if successful lets send the message
mail($to, $subject, $email);
echo('success'); //return success callback
} else {
echo('An invalid email address was entered'); //email was not valid
}
?>
Does anyone have any suggestions as to why this isn't working like it should. It seems to just lock up when I submit. Any help would be appreciated. Thanks!
Recommendations
Get firebug or httpfox to debug ajax scripts. You can see all requests made and the post/get variables.
Dont use eregi use preg
Dont use preg to validate email use php's filter functions
Another debugging idea: set the $_POST vars above the email.php code and visit the email.php in your browser to see if its working.
Related
I am using a form to get newsletter sign ups on my website. I am using a contact.php file which works well but there is no validation so I occasionaly and sometimes frequently get blank responses.
I'm not sure why this is, but I believe I need validation.
This is my original code
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
and this is the code I tried to add to validate but it doesnt work.
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "jcash1#gmail.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
/* Validation */
$error=0; // check up variable
$errormsg = '<ul class="errorlist">';
/* get it checking */
if(!check_email($email))
{
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
}
$errormsg .= '</ul>';
if($error == 0) {
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo 'error|'. $errormsg;
}
?>
Can anyone offer some insight?
I cannot for the life of me get this to work...
I am getting an Error with the plugin and I have loaded it correctly
so I tried adding this :
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
like so:
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo("$email is not a valid email address");
}
?>
Which is not working. I think it is beauce I have implemented the code in the wrong place but I am not sure. Any help would be greatly appreciated.
You can use filter_var() function in PHP for validating email addresses.
For simply validating email addresses in PHP you can use it like this,
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Valid email";
}
And your code can be improved like this.
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
}
else {
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
echo '</ul> error|'. $errormsg;
}
If you want to know more about it, visit official PHP documentation page here : http://php.net/manual/en/filter.filters.validate.php
Or use jquery validation plugin. I highly recommend it.
Code will look similar to below
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
You can use server side validation by using this code
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
im getting the "invalid email address"
all is hardcoded for testing, what is missing? thanks!
<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php
/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$email = $HTTP_POST_VARS['example#example.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!preg_match("/\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
echo "<h4>Invalid email address</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
echo "<h4>No subject</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
}
/* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
elseif (mail($email,$subject,$message)) {
echo "<h4>Thank you for sending email</h4>";
} else {
echo "<h4>Can't send email to $email</h4>";
}
?>
</body>
</html>
Change
$email = $HTTP_POST_VARS['jaaanman2324#gmail.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
to
$email ='jaaanman2324#gmail.com';
$subject ='subjectaaa';
$message = 'messageeeee';
I think you want it to be hardcoded like this:
$email = 'jaaanman2324#gmail.com';
Otherwise you are trying to get the value out of HTTP_POST_VARS with the key of jaaanman2324#gmail.com
First, don't use $HTTP_POST_VARS, it's $_POST now.
Second, by writing $HTTP_POST_VARS['jaaanman2324#gmail.com'] you're looking for table element with juanman234#gmail.com key.
That's not what you wanted to do.
If you want to hardcode it, write
$email = 'jaaanman2324#gmail.com';`
if not, write
$email = $_POST['email'];
to get email field from form.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I'm trying to build a form using php error checking on the same page.
Everything seems to be working fine except redirecting visitors to another page on my website (thanks.html) after they've filled in the form correctly. First an email is sent to an email address provided at the top of my code and after that visitors should be redirected to the thankspage, which I can't get to work.
The redirecting is this part in my code:
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
Here's what I have in total:
<?php
/* Set e-mail recipient */
$myemail = "myemail#gmail.com";
if (!$_POST['submit'])
{
form();
} else {
if (empty($_POST['name'])) { $error0='<br>name'; }
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email_address'])) { $error2='<br>Valid email address'; }
if (empty($_POST['phonenumber'])) { $error1='<br>phonenumber'; }
if (empty($_POST['comment'])) { $error3='<br>comment'; }
$error_messages = $error0.$error1.$error2.$error3;
if ($error_messages)
{
echo "Please ensure the following fields are completed before submitting your form:<strong>". $error_messages ."</strong><br><br>";
form();
} else {
$name = $_POST['name'];
$email_address = $_POST['email_address'];
$phonenumber = $_POST['phonenumber'];
$comment = $_POST['comment'];
/* Message for the e-mail */
$message = "
New contact request:
Name: $name
Email address: $email_address
Phonenumber: $phonenumber
comment: $comment
";
$subject = "Contact";
$headers = "From: $email_address";
/* Send the message using mail() function */
mail($myemail, $subject, $message, $headers);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
}}
?>
When checking for errors I get this result:
Warning: Cannot modify header information - headers already sent by (output started at form.php:11).
Form.php:11 is this line of code:
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email_address'])) { $error2='<br>Valid email address'; }
So after viewing other posts on stackoverflow I guess the issue might be whitespace or a header that has already been sent. But I still I can't it to work.
Could somebody help out and give a suggestion to fix this?
You are correct - You can't redirect if you've output anything to the browser. This goes for spaces at the beginning, anything really.
To get around this, check out the ob_* functions on php.net. Specially, check out flush. You'll be able to bypass this.
Hope that helps. Post again if you have ob_* issues.
As a side note, eregi has be deprecated as of 5.3.0 so its probably not a good idea to use it. Instead of using
eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email_address'])
use
filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL)
see http://php.net/manual/en/function.filter-var.php for more info.
Regards
Hi there I have edited some code I have found on-line and everything works besides the validation. It always seems to send an email even when all fields are blank on the contact form that I've created. It is definitely an easy fix but I'm new to this so any help means a great deal to me!!
Thanks.
Heres the code Im using for the php script:
/////////////////////////////////////////////////////
<?php
// Contact subject
$subject ="$Email Enquiry";
// Details
$message=("$cComment") ;
// Mail of sender
$mail_from="$cEmail";
// From
$header="from: $cName <$mail_from>";
// Enter your email address
$to ='info#blahblahblah.net';
$send_contact=mail($to,$subject,$message, $header);
// Check, if message sent to your email
// display message "We've recived your information"
if($mail_from != "Email"){
header('Location:thanksemail.php');
}
else {
header('Location:emailfail.php');
}
?>
You need to check if the variables are empty before sending the email. You can do this like so:
if(!empty($variable) and
!empty($variable2)) {
// send the email out here
}
I am using the empty() function here to detect if the values are empty or not. The following values are considered to be empty values:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
I would also avoid using the standard PHP mail function and instead use a library such as PHPMailer or SwiftMailer to send out your emails instead. They give you more flexibility and both have a much nicer API to work with.
You haven't got any checking code. The code that sends the mail is $send_contact=mail($to,$subject,$message, $header);
The checking must be before this code
Try this
if($subject!="" && $cComment!="" && $cEmail!="" && $cName!="" && $mail_from!=""){
$send_contact=mail($to,$subject,$message, $header);
if($mail_from != "Email"){
header('Location:thanksemail.php');
}
else {
header('Location:emailfail.php');
}
}else{
header('Location:emailfail.php');
}
Just as a side note, you can save yourself a line or two of code by verifying if the e-mail was sent like:
if(mail($to,$subject,$message, $header)){
header('Location:thanksemail.php');
}else {
header('Location:emailfail.php');
}
If it comes back true, it was sent. If false, it was not sent.
You have put the mail() function outside your if() statement.
Just move it (and complete your if with the other fields):
<?php
if(!empty($mail_from) && !empty($Email)) {
mail($to, $subject, $message, $header);
header('Location:thanksemail.php');
} else {
header('Location:emailfail.php');
}
I posted a similar question earlier, just I did not realize that the code I put had an obvious bug in it (not supplying the data) which I new existed. Now I am redoing it with that because I am still having the problem.
I have this AJAX:
function sendMail(){
$.ajax({
type: "POST",
url: "../prestige-auto/php/sendMail.php",
data: {"message" : $('#contactMessage').html(),
"email" : $('#contactEmail').val(),
"name" : $('#contactName').val()},
success: function(result){
if (result == 'success') {
alert(result);
} else {
alert(result);
}
}
});
};
$('#submitContact').click(function(){
sendMail();
})
and this PHP:
<?php
$trimmed = array_map('trim', $_POST);
$message = $trimmed['message'];
$email = $trimmed['email'];
$name = $trimmed['name'];
if (empty($message)) {
$message = FALSE;
}
if (empty($email)) {
$message = FALSE;
}
if (empty($name)) {
$message = FALSE;
}
if ($message && $email && $name){
$body = "From: $name.\n \n $message";
mail(/*some email*/, 'Website Contact Form Submission', $body, "From: $email");
echo ('success');
}
echo($message.' '.$email.' '.$name);
?>
All the html elements defined exist. When I run it all that returns is a blank alert box (meaning that the PHP script did not print out success). Any idea why it is not sending the mail?
You didn't exit after echoing out the 'success' - PHP hasn't stopped processing yet, so it just continues to the next line, and renders out echo($message.' '.$email.' '.$name); as well.
This means your JS test is comparing success with success$message $email $name, which is always false.
If you want to stop processing, you have two choices: either exit or die (don't do this), or wrap the rest of the code in an else tag, like this:
if ($message && $email && $name){
$body = "From: $name.\n \n $message";
mail(/*some email*/, 'Website Contact Form Submission', $body, "From: $email");
echo ('success');
} else {
echo($message.' '.$email.' '.$name);
}
Also, make sure you don't end your PHP scripts with ?> ! This almost always leads to problems later where the PHP script renders out some unwanted white space at the end, which would also fail.
Don't use array_map('trim', $_POST) http://www.php.net/manual/en/function.trim.php#96246
check ajax response first to see if there is any error occurs.