Send mail from website ubuntu, php, ajax - php

I have a website with a form where you can send a message to my email adress. But it doesn't work yet. I am not really sure what is required to do this. Here is what i have done so far:
The PHP:
<?php
if (isset($_POST['from']) && isset($_POST['header']) && isset($_POST['message'])) {
$to = "example#awesomemail.com";
$subject = $_POST['from'];
$body = $_POST['message'];
$headers = $_POST['header'];
if (mail($to, $subject, $body, $headers)) {
echo("<p>Email successfully sent!</p>");
echo json_encode('success');
} else {
echo("<p>Email delivery failed…</p>");
echo json_encode('failed');
}
}
?>
The JS:
$.ajax({
type : "POST",
url : "sendmail.php",
data: {"from": from, "header": header, "message": message},
dataType: "json",
success: function(msg){
alert(msg);
}
});
Is there something wrong with my code or am i missing something?
The email is supposed to be sent to a gmail account.

Not enough points to comment on question... but just wanted to confirm you have an Mail Transfer Agent set up on the system. If not, that may be the culprit.
If this hasn't yet been done yet, you can refer to sendmail: how to configure sendmail on ubuntu? or https://help.ubuntu.com/12.04/installation-guide/i386/mail-setup.html to get that going.

Try it like this , try sending a complete json response from the server side to client side for it to parse..
PHP :
<?php
if (isset($_POST['from']) && isset($_POST['message']))
{
$to = "example#awesomemail.com";
$subject = $_POST['from'];
$body = $_POST['message'];
$headers = urldecode($_POST['header']);
if (mail($to, $subject, $body, $headers))
echo json_encode('success');
else
echo json_encode('failed');
}
else
echo json_encode('failed');
?>
JS :
$.post('sendmail.php',{"from": from ,"header" :header, "message":message},function(response)
{
var response = $.parseJSON(response);
console.log(response);
});

if sending header is a problem you can do like this:
first concat all values into one variable
var string = 'mail='+from+'/'+header+'/'+message;
$.ajax({
type : "POST",
url : "sendmail.php",
data: string,
dataType: "json",
success: function(msg){
alert(msg);
}
});
sendmail.php
<?php
if (isset($_POST['mail']) && !empty($_POST['mail'])) {
$msg = explode('/','$_POST['mail']');
$to = "example#awesomemail.com";
$subject = $msg[0];
$headers = $msg[1];
$body = $msg[2];
if (mail($to, $subject, $body, $headers)) {
echo("<p>Email successfully sent!</p>");
echo json_encode('success');
} else {
echo("<p>Email delivery failed…</p>");
echo json_encode('failed');
}
}
?>
This answer is just another alternative way, more based on your comment.
(you can perform javascript validation before submitting form or with condition before even entering jquery/ajax)

Related

How to pass values from a html page using jQuery to PHP and get a response back?

I am trying to pass the values from jQuery to PHP. Here is my code,
jQuery Function:
$(document).ready(function () {
$("#contact_form").submit(function () {
var RequesterName = $("#RequesterName").val();
var Requestoremail = $("#Requestoremail").val();
var Subject = '[Request] Mail Subject';
$.ajax({
type: 'post',
dataType: 'json',
url: 'sendmail.php',
data: { RequesterName_val: RequesterName, Requestoremail_val: Requestoremail, Subject_val: Subject },
success: function (data) {
alert('Mail Sent Successsfully');
}
});
});
})
and PHP:
<?php
$to = $_POST['RequesterName_val'];
$subject = $_POST['Subject_val'];
$RequesterName = $_POST['RequesterName_val'];
$Requestoremail = $_POST['Requestoremail_val'];
$message = "RequesterName:".$RequesterName." , Requestoremail:".$Requestoremail." ";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <'.$Requestoremail.'>' . "\r\n";
$headers .= "Reply-To: '.$Requestoremail.'\r\n";
if (mail($to,$subject,$message,$headers)) {
echo "Success";
} else {
echo "Error";
}
die();
?>
It seems mail is triggering from php but I am not getting a response back and "Mail Sent Successfully" is not displaying in jQuery? How can i get a response for success and failure of mail trigger?
Your $.ajax call says that the response should be JSON, but you're just returning plain text. When jQuery gets an error trying to parse the JSON, it doesn't call the success: callback.
You can either correct the PHP so it returns JSON:
echo json_encode(mail($to,$subject,$message,$headers));
die();
Then in the success function you would write:
success: function(data) {
if (data) {
alert('Mail sent successfully');
} else {
alert('Mail not sent');
}
}
or you can change the $.ajax call to use dataType: 'text', and the callback would be:
success: function(data) {
if (data == 'Success') {
alert('Mail sent successfully');
} else {
alert('Mail not sent');
}
}

asynchronous email php + jquery

I need to send email asynchronously.
For that I have a jQuery ajax client and PHP backend to actually send eMail, still AJAX's success method is not being called. I understand it is simple, but yet doesn't seem to be working. Can somebody please take a look at my code and see what I'm doing wrong? Really appreciate it.
$.ajax({
type: "POST",
url: "mail.php",
data: {name: "manu", email: "abc#abc.com"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('mail sent');
$('#divToBeWorkedOn').html(msg);
}
});
and I have mail.php
<?php
header("Content-type: application/json");
$name = trim($_POST['name']);
echo $name
$email = trim($_POST['email']);
$msg="my email";
$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 1;
?>
I see 2 problems.
you're echoing just 1, its not JSON. So in your PHP code do json_encode("msg"=>"1");
In my experience, if you have this
header("Content-type: application/json");
OR header("Content-type: json/text");
You won't get any result in jquery success or error blocks.
success: function(msg) {
alert(msg);
}
the msg would return null value (or nothing). The alert will happen but will show something like object object.

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

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.

display error from jquery post

i am posting to a mailer.php file.
mailer.php
<?php
if(isset($_POST['submit'])) {
$to = "testabc#gmail.com";
$subject = "Contact via website";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";
echo "Data has been submitted to $to!";
mail($to, $subject, $body);
} else {
echo "blarg!";
}
?>
here is my js code
$('.submit').click(function(){
$('span.msg').css({'visibility': 'visible'}).text('Sending...');
$.post("mailer.php", $(".contactPage").serialize(),
function(data){
$('span.msg').text('Your Message has been received. Thank you').show();
});
return false;
});
I am getting message of success but email is not received. What i am doing wrong? How to get error detail from mailer.php file and showing in span.msg?
if(mail($to, $subject, $body)){
echo "success";
}else{
echo "fail";
}
JS:
$('.submit').click(function(){
$('span.msg').css({'visibility': 'visible'}).text('Sending...');
$.post("mailer.php", $(".contactPage").serialize(),
function(data){
if(data == 'success'){
$('span.msg').text('Your Message has been received. Thank you').show();
}else{
$('span.msg').text('Your Message has failed. Thank you').show();
}
});
return false;
});
On this page under the Return Values section it says:
Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.
So just check if it is returning true or false.
EDIT: Also try checking your spam folder. Perhaps someone on your shared hosting provider is sending spam.

Categories