asynchronous email php + jquery - php

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.

Related

How to get the message from a php file and send to another php file using ajax?

$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function(result){
alert(msg);
}
});
I have written a ajax file to send some parameters to another file insert.php to send these parameters as mail. If the mail send has been successfully, it should send a message back to the main file to display it there. I have written the code for insert.php shown below :
<?php
$date=$_POST['date'];
$newDate = date("d-m-Y", strtotime($date ));
$time=$_POST['time'];
$name=$_POST['name'];
$number=$_POST['number'];
$mail=$_POST['mail'];
$pname=$_POST['pname'];
$ptype=$_POST['ptype'];
$gender=$_POST['gender'];
$comments=$_POST['comments'];
$to = 'df#gmail.com';
$subject = 'Enquiry !!!!';
$message = ' A Customer has made a enquiry about a package " '.$pname.' " whose Name is " '.$name.' " with Email-id '.$mail.' and who is a '.$gender.' and Contact Number is '.$number.' and has send a message " '.$comments.' " on Date '.$newDate .' and Time '.$time;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$retval = mail($to, $subject, $message, $headers);
if($retval == true)
{
$msg = "YOUR ENQUIRY HAS BEEN SEND!!!!";
echo $msg;
}else {
$msg = "YOUR ENQUIRY HAS NOT BEEN SEND!!!! PLEASE TRY AGAIN !!!";
echo $msg;
}
?>
I want to send the $msg value back to the php file from where the control came to display it there. How to get that message inside success function ? I tried to alert it, but it is not working.
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function(result){
alert(result);// the resiult is your message.
}
});
What ever you echo from insert.php the result is your message . please try this you will get the result. result is parameter for the function. The output of the ajax page will catch here only and process this result only.

Cannot send email using mail function

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!

AJAX post call to php script not working

I cant understand why the following is not working, I am trying to call a php script to send an email, but i dont think my ajax call is calling the php script at all, I just get an error returned.
My ajax call:
var name_field = $('#cf_name').val();
$.ajax({
type: 'post',
url: 'contact.php',
data: {'name_field' : name_field },
dataType: 'json',
success: function(data) {
if(data.status == 'success')
alert("Thank you for subscribing!");
else if(data.status == 'error')
alert("Error on query!");
},
error: function(err) {
alert(err.responseText);
}
});
My php script:
$field_name = isset($_POST['name_field']);
$field_email = 'name#email.com';
$field_phone = '12345';
$field_message = 'Hello World!';
$mail_to = 'emailaddress#email.com';
$subject = 'Message from a website visitor '.$field_name;
$body_message = 'This message has been sent via website:'."\n\n";
$body_message .= 'From: '.$field_name."\n\n";
$body_message .= 'E-mail: '.$field_email."\n\n";
$body_message .= 'Phone Number: '.$field_phone."\n\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) {
$response_array['status'] = 'success';
}
else {
$response_array['status'] = 'error';
}
header('Content-type: application/json');
echo json_encode($response_array);
If i navigate to the url directly the php works as intended, but i can not get the ajax post to call it.
$field_name is not an actual string, it's a boolean since you used $field_name=isset($_POST[name_field']). Remove the isset().
See this: jQuery Ajax post cancelled i'm not a js expert but I agree with your problem being the async execution of your ajax call, since it takes a while to send an email, maybe isn't completed in time for your js
See this nice explanation about the "async" propertie in the ajax call:
What does "async: false" do in jQuery.ajax()?
And see this question/answer:
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
You should check url: contact.php as you did not specify the full URL, so your post is going to a relative path. The root path will be same current script path.

Send mail from website ubuntu, php, ajax

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)

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

Categories