Send email with Ajax in Wordpress - php

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.

Related

Contact forms ajax PHP call prints echo on screen instead of returning success

I'm trying to set up a small personal page based on kite. It comes along with a sleak contact form.
However, I was not able to get this contact form to work. After many hours, I managed to get it to send emails, but now it doesn't return a proper 'success' status, so the contact form gets updated. Instead, the echo 'success' in the called php gets printed on screen. The eMail, however, is being sent.
Any ideas what I am doing wrong?
HTML
<form id="contact-form" action="email.php" method="post" class="clearfix">
<div class="contact-box-hide">
//in here is the contact-box form
</div><!-- /.contact-box-hide -->
<div id="contact-message" class="contact-message"></div>
//This is the div, in which the success message should be posted
</form><!-- /#contact-form -->
AJAX Call
$.ajax({
type: "POST",
url: "email.php", //if I use this line, the mail is not being sent, but the email.php script hands over a proper success message to the ajax call
url: $(form).attr('action'), //if I use this line, the mail will be sent, but the email.php script prints its echo on a blank page
data: data_string,
//success
success: function(data) {
$('.contact-box-hide').slideUp();
$('.contact-message').html('<i class="fa fa-check contact-success"></i><div>Super, die Nachricht ist raus.</div>').fadeIn();
},
error: function(data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-exclamation contact-error"></i><div>Mist. Da ist was schief gegangen. Versuchs später nochmal.</div>').fadeIn();
}
}) //end ajax call
email.php
<?php
if($_REQUEST['first_name'] == '' || $_REQUEST['contact_email'] == '' || $_REQUEST['message'] == ''):
return "error";
endif;
if (filter_var($_REQUEST['contact_email'], FILTER_VALIDATE_EMAIL)):
$subject = 'Mail von der Hochzeitsseite: ' . $_REQUEST['contact_subject']; // Subject of your email
// Receiver email address
$to = 'my#mailadress.de';
// prepare header
$header = 'From: '. $_REQUEST['first_name'] . " " . $_REQUEST['last_name'] . ' <'. $_REQUEST['contact_email'] .'>'. "\r\n";
$header .= 'Reply-To: '. $_REQUEST['first_name'] . " " . $_REQUEST['last_name'] . ' <'. $_REQUEST['contact_email'] .'>'. "\r\n";
// $header .= 'Cc: ' . 'example#domain.com' . "\r\n";
// $header .= 'Bcc: ' . 'example#domain.com' . "\r\n";
$header .= 'X-Mailer: PHP/' . phpversion();
$message = $_REQUEST['message'] . "\n\n\n\n\n\n\n\n\n";
$message .= 'Name: ' . $_REQUEST['first_name'] . " " . $_REQUEST['last_name'] . "\n";
$message .= 'Email: ' . $_REQUEST['contact_email'] . "\n";
// Send contact information
$mail = mail( $to, $subject , $message, $header );
echo "success";
else:
return "error";
endif;
?>
Your form is getting submitted directly to email.php, it is not going through ajax. That's what the action attribute is all about:
<form id="contact-form" action="email.php"
To use ajax instead, you need to remove the action attribute from the form and add a click handler to your submit button/link. For example:
<button onclick="doAjaxCall()">Submit Email</button>
The ajax call itself, would look something like this:
$.ajax({
type: "POST",
url: "email.php",
data: {
name: $('#name').val(),
address: $('#address').val(),
...
},
...

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!

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

Can I reset a form with PHP?

is possible to use php to reset a form without refresh?
how can i archive this?
or is possible to do it with js?
most important is do it without to refresh the page and dont add another button for this(that's because the design)
any idea?
thanks
am working with recaptcha on my form and once i submitted the information i want to send a message
this is my js code
function validateCaptcha(){
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
nameField = $("input#name").val();
emailField = $("input#email").val();
phoneField =$("input#phone").val();
reasonField =$("select#reason").val();
messageField =$("textarea#message").val();
var html = $.ajax({
type: "POST",
url: "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField +"&name="+ nameField +"&email=" + emailField +"&phone="+ phoneField + "&reason=" + reasonField +"&message=" + messageField,
async: false
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
$("#thanks").html("Thank you, we going to keep in touch with you soon. ");
return false;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
this is my php code
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$reason = $_POST['reason'];
$message = $_POST['message'] ;
if (empty($name)|| empty($email) || empty($message))
{
}
else
{
$resp = recaptcha_check_answer (PRIVATEKEY, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$header = 'From: ' . $email . " \r\n";
$msg = "Sent from: " . $name . "\r\n";
$msg .= "Email: " . $email . " \r\n";
$msg .= "Phone: " . $phone . " \r\n";
$msg .= "Contact reason:" . $reason . " \r\n";
$msg .= "Message: " . $message . " \r\n";
$to = 'patricia#anetdesign.com';
$subject = 'Emailmakers contact page';
mail($to, $subject, utf8_decode($msg), $header);
?>success<?
}
else
{
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
}
Well, once you sed the ajax request if the captcha fails then just reload the entire form.
Say you have only the form in myform.php and you include it in your main page, when the captcha does not match you can just reload the form. Like this:
if (html != "Success")
{
$("#divThatHoldsTheForm").html(html)
}
and in your myform.php you have only:
<form action="..." method="POST">
<!-- some inputs -->
</form>
Use the reset() function. If you have a form named frm then use can use frm.reset().
Or just write code to first get all textboxes and set its value attribute to "". this wont need to refresh your page
Using PHP mean refreshing the page (only in case of ajax) so i suggest you try to use javascript instead of php to this task

Categories