Cannot send email using mail function - php

First question and first time looking at PHP so please bear with me.
I currently have the below jQuery which is calling a php file:
$(document).on('click', '#btnContactUs', function () {
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("input#message").val();
var dataString = 'name='+ name + '&email=' + email + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "php/message.php",
data: dataString,
success: function(response) { alert(response); }
});
return false;
});
The console is logging the call as successful (XHR finished loading: POST "php/message.php").
Below is the full script in the file:
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
The email is not being sent/received (I am checking Spam also).
The files are hosted on a web server which has PHP installed. The alert box is popping up, but empty. The initial AJAX call is made from a submit button on a webpage.
EDIT: I am sending this to my personal email, which I have not included above.
EDIT: Even when visiting the URL of the script the email is still not being sent.
FINAL EDIT: The resolution is that my server did not have PHP mail installed - it is not supported as it is considered unreliable and therefore they recommend SMTP. To figure this out I used DrewT's solution of using SSH to check for "which sendmail"
Hope this scenario helps someone in the future.
Thanks all.

What seems to be happening is you are not sending your information in the correct format because you don't parse your var dataString on the server. I would try something like:
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("input#message").val();
Then in your post function:
$.ajax({
type: "POST",
url: "php/message.php",
data : { name: name, email: email, subject: subject, message: message },
success: function (response, status, err) {
// do stuff...
// NOTE: don't return false or it won't send
// 'return false' only if the form is incomplete
// and you don't want the email sent out prematurely
}
});
Then to receive these vars in your PHP:
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
Now you can send an email like this:
// Enter your send email address
$to = 'email#example.com';
// Add your headers
$header = "from: $name <$email>";
// only send it if we have all the data we need
if( $subject !== "" || " " && $message !== "" || " " && $name !== "" || " " && $mail_from !== "" || " " ) {
$send_contact = mail($to,$subject,$message,$header);
// check if message was sent
// and provide some formatting (html) to send along in our response
if ($send_contact) {
echo '<div class="msg-sent">
Your message was sent successfully yay!
</div>';
}
else {
echo '<div class="msg-send-failed">
SEND FAILED :0
</div>';
}
}
else {
echo '<div class="msg-had-empty">
YOU HAD EMPTY POST VARIABLES :0
</div>';
}
Beyond that you will need to debug using the networks tab in your browser's inspector./ good luck!

Related

Contact form sends blank emails

My contact form is not including message and other informations in emails.
There is 'Unknown sender' and 'No subject'. Email contains my tags (from:, subject:, message:) but no content is written after them.
I have tried a few other scripts, but they gave the same result.
My JS code
(function($){
$(document).ready(function() {
$('#submit-form').click(function(e){
e.preventDefault();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $('#rp_name').val(),
email = $('#rp_email').val(),
subject = $('#rp_subject').val(),
message = $('#rp_message').val(),
data_html,
success = $('#success');
if(name === ""){
$('#rp_name').val('Please enter your name.');
}
if(subject === ""){
$('#rp_subject').val('Please enter your name.');
}
if(email === ""){
$('#rp_email').val('Your email is required.');
}else if(reg.test(email) === false){
$('#rp_email').val('Invalid Email Address.');
}
if(message === ""){
$('#rp_message').val('Message is required.');
}
if(message !== "" && name !== "" && reg.test(email) !== false) {
data_html = "name=" + name + "&email="+ email + "&message=" + message + "&subject="+ subject;
alert(data_html);
$.ajax({
type: 'POST',
url: 'php_helpers/contact_form.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
success.html('<div class="alert alert-success">Message <strong>successfully</strong> sent!</div>') ;
$('#rp_name').val('');
$('#rp_email').val('');
$('#rp_message').val('');
}else{
success.html('<div class="alert alert-error">Message <strong>not</strong> sent! Please Try Again!</div>') ;
}
}
});
}
return false;
});
});
})(jQuery);
My PHP code
<?php
$to = 'email'; // I changed it
$subject = $_POST['subject'];
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$fields = array(
0 => array(
'text' => 'Imie',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email',
'val' => $_POST['email']
),
2 => array(
'text' => 'WIADOMOSC',
'val' => $_POST['message']
)
);
$message = "";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '. $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
if ($message){
echo 'sent';
}else{
echo 'failed';
}
} else {
echo "Don't access this file directly";
}
?>
I'll be glad for any hints.
There as i check your contact.php file code is ok. But you need one thing if use firefox. please console your code.I mean when you open firebug there will be one option console. with help you can check is your value along with variable is going or they empty.
I think your value is not going to PHP file. use console and you can easily bug your value.
I hope this make sense for you.
Check if your php script receives name, email and message. You can check it using
var_dump($_POST);
If server doesn't receive these variables, try to send data_html as an object:
change
data: data_html,
to
data: {name: name, email: email, message: message}
I didn't test it, but I always use this way of sending data from js to server.
You are using two dollar symbols in the line: $$headers = 'MIME-Version: 1.0' . "\r\n"; Please remove "$" and try again.
Thanks for all your responses. I finally manage to find a solution. I haven't used firebug before, but thanks to it I could find the error message. Now the script is working fine.
It wasn't in code, but in .htaccess rewrite rule for .php files which was couseing 301 error for ajax request (../contact instead of ../contact.php).
I have one .php page (file uploader) and I thought that adding another seo-friendly link rule for it would be a good idea.

jQuery AJAX contact form with PHP mailer jumping to mail page

I'm making a simple contact form, I have an old school php mailer mail.php and a jQuery front page from where I'm calling it.
As I wanted it to work, it should've stayed on same page, but it actually jumps to mail.php and displays the message
Thank you for contacting me. I'll try to reach you ASAP.
Though it does send the mail, thats still not acceptable as that was not my intention. Can anybody find out what I'm doing wrong here ?
Any help appreciated.
PHP:
<?php
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
$emailTo = 'myEmail#gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
echo "Thank you for contacting me. I'll try to reach you ASAP.";
return true;
?>
FORM (Lot of bootstrap tags there, so to keep it clean I'm just posting ):
<form class="form" action="mail.php" method="post" id="contact-form">
</form>
And here goes my AJAX:
var data_string = jQuery('#contact-form').serialize();
jQuery.ajax({
type: "POST",
url: "mail.php",
data: {name:name,email:email,message:message},
timeout: 6000,
error: function(request,error) {
if (error == "timeout") {
jQuery('#timedout').fadeIn('slow');
setTimeout(function() {
jQuery('#timedout').fadeOut('slow');
}, 3000);
}
else {
jQuery('#state').fadeIn('slow');
jQuery("#state").html('The following error occured: ' + error + '');
setTimeout(function() {
jQuery('#state').fadeOut('slow');
}, 3000);
}
},
success: function() {
jQuery('span.valid').remove();
jQuery('#thanks').fadeIn('slow');
jQuery('input').val('');
jQuery('textarea').val('');
setTimeout(function() {
jQuery('#thanks').fadeOut('slow');
}, 3000);
}
First i will recommend you to use jQuery Form Plugin, very helpful for this kind of ajax post and validations.
jQuery Form
Second, you can use event.preventDefault(); to avoid the default action of the link but it will really depend on how are you triggering your form to the ajax code
event.preventDefault

Use Ajax to show failure message when PHP filter validate email detects an invalid submit

It's the HTML contact form:
<form class="form" method="post" action="mail.php">
<label for="name">Name:</label>
<input class="name" type="text" name="name" value="" placeholder="Full Name" required>
<label for="email">Email:</label>
<input class="email" type="text" name="email" value="" placeholder="Email" required>
<label for="message">Message:</label>
<textarea class="message" rows="4" cols="20" name="message" placeholder="Type..." required></textarea>
<input type="submit" value="Send">
It's the Ajax I use for my contact form:
$('.form').submit(function() {
var name = $(".name").val();
var email = $(".email").val();
var message = $(".message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function() {
$(".form").hide();
$(".notice").fadeIn(400);
}
});
return false;
});
And it's my mail.php (I found here):
<?php
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
} else {
header("Location: your_form.html");
}
I just want to add an "Invalid Email Address" message to my form with Ajax (in order to show besides the form, Not in another page)
In the current form when the user submit a filled and valid inputs, it shows a Success message (.notice), but nothing happen when you submit the form with an invalid email address.
You can try passing arrays from your PHP script back to your AJAX response as data, and let your script handle whatever that is passed back :) In my example below, I have chosen to pass the PHP response back to your AJAX script using the json_encode function, and arbitrarily selected a type of status code that will be read by your JS function to take appropriate action :)
Also, in order your $.ajax to read JSON data correctly, you should include the line dataType: "json" in the function.
Overall, the suggested changes will be:
Echo a response from your PHP script in JSON format using json_encode()
Allows your PHP script to pass the response to your JS script
Ensure that your AJAX function reads the JSON format, and then take the appropriate action
For example, in your PHP script, you can use:
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
// If email is valid
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if(mail($recipient, $subject, $formcontent, $mailheader)) {
// If mail is sent
// Status is arbitrary. You can use a string, number... I usually use numbers
$resp = array("status"=>1, "message"=>"Mail successfully sent.");
} else {
// If sending failed
$resp = array("status"=>2, "message"=>"Error with sending mail.");
}
} else {
// If email failed filter check
$resp = array("status"=>3, "message"=>"You have provided an invalid email address. Please check the email address provided.");
}
// Echos the $resp array in JSON format, which will be parsed by your JS function
echo json_encode($resp);
In your JS file, you can parse the JSON response:
$('.form').submit(function() {
// Define variables to construct dataString. You don't need to use var to declare each variable individually ;)
var name = $(".name").val(),
email = $(".email").val(),
message = $(".message").val();
// Construct dataString
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
// Ajax magic
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data) {
if(data.status == "1") {
$(".form").hide();
$(".notice").fadeIn(400);
} else if (data.status == "2") {
// Error handling for failure in mail sending
} else if (data.status == "3") {
// Error handling for failure in email matching
} else{
// Catch all other errors
}
}
});
return false;
});
First change your PHP to output Invalid Email Address in case for invalid email address, then check if that message exists as response from ajax:
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
}else{
echo "Invalid Email Address";
}
And change ajax to:
$('.form').submit(function() {
var name = $(".name").val();
var email = $(".email").val();
var message = $(".message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function(data) {
if(data.indexOf("Invalid Email Address") >= 0){
alert("Invalid Email Address");
}else{
$(".form").hide();
$(".notice").fadeIn(400);
}
}
});
return false;
});
You're going to want to use regular expressions for this, and filter_var. We'll be validating in both Javascript and PHP because the user might not have Javascript enabled.
The regular expressions I normally use to validate emails is this:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
When your forms gets submitted you'll want to run something like this:
var email = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if(email.test($('.email').val()) === FALSE) {
$('.notice').html('<strong>Invalid email address!</strong>').show();
return false;
}
In your PHP once you've checked if the POST request is valid and has all the fields you need you'll want to run filter_var with the FILTER_VALIDATE_EMAIL parameter. filter_var returns a boolean.
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
echo 'Invalid email address!';
exit;
}

Sending Email via PHP Not Working

I have a site running on Windows Azure that contains a simple contact form for people to get in touch. Unfortunately, that form isn't work right now...
I have an index.php file that contains the form:
<div class="form">name="name" placeholder="Name" id="contactname" />
<input type="text" name="email" placeholder="Email" id="contactemail" />
<textarea name="message" placeholder="Message" id="contactmessage"></textarea>
<button>Contact</button>
</div>
I then have a JS file like this:
if ($('#contact').is(":visible")) {
$("#contact button").click(function() {
var name = $("#contactname").val();
var message = $("#contactmessage").val();
var email = $("#contactemail").val();
var emailReg = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$/;
// client-side validation
if(emailReg.test(email) == false) {
var emailValidation = false;
$('#contactemail').addClass("error");
}
else
$('#contactemail').removeClass("error");
if(name.length < 1) {
var nameValidation = false;
$('#contactname').addClass("error");
}
else
$('#contactname').removeClass("error");
if(message.length < 1) {
var messageValidation = false;
$('#contactmessage').addClass("error");
}
else
$('#contactmessage').removeClass("error");
if ((nameValidation == false) || (emailValidation == false) || (messageValidation == false))
return false;
$.ajax({
type: "post",
dataType: "json",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html('<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>');
}
});
return false;
});
};
and finally, a php file to send the email called send-email.php:
$destination = 'info#clouddock.co'; // change this to your email.
// ##################################################
// DON'T EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING
// ##################################################
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $name;
$headers = "From: ".$name." <".$email.">\r\n" .
"Reply-To: ".$name." <".$email.">\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
mail($destination, $subject, $message, $headers);
}
When I fill in the contact form, the JS validation appears to be working, and when I click send the 'Thanks for getting in touch...' text appears, as if the message has been sent. But I don't receive any email. Can anyone advise as to where the problem might be? Could it be Azures configuration blocking the messages from being sent out?
You are using $("#contact").serialize() to get data to send but you've got no elements with ID contact.
You should use $("#contactname, #contactemail, #contactmessage").serialize() (and fix first input ;) ).
And always validate input data in PHP, not only in JS!
Of course it will display the thanks message, all it needs is a response back from the server. What you need is to test whether the mail actually sent or not, then return that back to your original script to determine what message to show.
if(mail($destination, $subject, $message, $headers)) {
return '<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>';
} else {
return '<p class="fail">The e-mail failed to send.</p>';
}
And then set your AJAX to:
$.ajax({
type: "post",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html(data);
}
});
You'll probably find that you get the fail message, and that could well be the setup of your server, or it could be you not passing the right thing to the mail() function. You then need to debug your script to find out whether the right information is being passed etc.
With Windows servers they need to be configured to pass all mail from the mail() function to an SMTP server, so if that's not been done on your Azure server then your mail will instantly fail.

Send email with Ajax in Wordpress

i an new to wordpress theme development, i need to send an email with ajax/PHP in wordpress
var dataString = 'name=' + name +
'&email=' + email +
'&contact=' + contact +
'&technology=' + technology +
'&budget=' + budget +
'&details=' + details;
alert(dataString);
$.ajax({
type: "POST",
url: "<?php bloginfo('template_url'); ?>/qoute-sent.php",
data: {name:'anas', Email: 'anas#yahoo.com'},
datatype: "html",
success: function() {
alert(sent);
}
all the code work till alert(dataString); but after that ajax does not works....
this is my php file code
$name=$_POST['name'];
$email=$_POST['email'];
// $contact=$_POST['contact'];
//$technology=$_POST['technology'];
// $budget=$_POST['budget'];
//$details=$_POST['details'];
//-------------for email setup----------------------------
$to = "stylegurupk#gmail.com";
//------------------------------------------
$message = " \n " .
"Name ".$name." \n " .
"Email : ".$email." \n " ;
//----------------------------------
$subject = "MWM Qoute Request";
$headers = 'From: '.$email . "\r\n" .
'Reply-To: '.$to . "\r\n" .
'X-Mailer: PHP/' . phpversion();
//echo "TO : ".$to."<br>";
//echo "FROM : ".$email."<br>";
//echo "<br>".$message;
mail($to, $subject,$message,$headers);
WordPress provides functionality and hooks to develop with AJAX to make it really easy. See the Codex.
You should also check out wp_mail for sending emails.
Remember that WordPress loads jQuery in noconflict mode, so your $ selector's should be 'jQuery'.
To prevent abuse you should consider adding a nonce to your script. WordPress handles that too :) See wp_create_nonce.
I think this is a good reference article once you have the bones in places
url: "<?php bloginfo('template_url'); ?>/qoute-sent.php",
Should the URL be "quote-sent.php"? Just checking.
Also, have you set up the AJAX actions for WP? It won't work without them. I'd generally do something like:
<?php
function my_send_email(){
doStuff(); // etc..
echo 'sent!';
die();
}
add_action('wp_ajax_my_send_email', 'my_send_email');
add_action('wp_ajax_nopriv_my_send_email', 'my_send_email');
?>
Like Mark said, I'd also recommend using wp_mail.

Categories