I am making a ajax form. I get the success message but I dont get any email, any thoughts?
send-form.php:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text']) && isset($_POST['email'])) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
//send email
mail( "mymail#email.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" . $_POST['email'] );
}
?>
functions.js:
$(function() {
// Contact Form
$("#contact").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var text = $("#text").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text;
$("#contact").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "send-form.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
}
})
return false;
});
});
index.html:
<form id="contact" method="post">
<fieldset>
<label>Your Name</label><br />
<input name="name" id="name" type="text">
<label>Your Email</label><br />
<input name="email" id="email" type="text">
<label>Your Question</label><br />
<textarea rows="10" name="text" id="text" ></textarea>
</fieldset>
<input type="submit" value="Send Message" name="submit">
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</form>
I have been siting with this in hours, trying to edit it with my own skill, but no success. This is what I got so far. I am getting the success message but no email sent to me.
Any Help is appreciated!
Related
I have created a custom html form on WordPress and placed it using HTML widget
<form id="form">
<label for="fname">Full Name</label>
<input type="text" id="fname" name="name" placeholder="Your name..">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Your email..">
<label for="contact">Contact number</label>
<input type="tel" id="contact" name="phone" placeholder="Your contact number..">
<label for="subject">Description</label>
<textarea id="subject" name="msg" placeholder="Tell us your requirements.." style="height:100px">
</textarea>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
and here is my js code
function myFunction() {
var name = document.getElementById("fname").value;
var email = document.getElementById("email").value;
var Contact = document.getElementById("contact").value;
var Message = document.getElementById("subject").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1=' + name + '&email1=' + email + '&contact=' + Contact + '&message=' + Message;
if (name == '' || email == '' || Contact == '' || Message == '') {
alert("Please Fill All Fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "ajaxjs.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
Now I want to send mail using this form data so How can I send email using WordPress wp-mail.php
First of all, you need to make some changes in your HTML and javascript and have do add few PHP code :
1) Change in form tag
<form id="form" method="post" action="">
2) Add a hidden field in the form with action name
<input type="hidden" name="action" value="my_form_submission">
3) add ajaxurl in functions.php file where you have enqueued your js file
add_action( 'wp_enqueue_scripts', 'your function' );
function enqueue_my_frontend_script() {
wp_enqueue_script( 'my-script', plugin_dir_url(__FILE__).'frontend-scripts.js', array('jquery'), null, true );
$variables = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_localize_script('my-script', "jsObj", $variables);
}
4) In your ajax call, change this
$.ajax({
type: "POST",
url: jsObj.ajaxurl, // this will get ajax url
data: $( "#form" ).serialize() , // send your form data with serialize mode
success: function(html) {
alert(html);
}
});
4) Add ajax actions in theme's functions.php file :
add_action('wp_ajax_my_form_submission', 'my_form_submission_callback');
add_action('wp_ajax_nopriv_my_form_submission', 'my_form_submission_callback');
function my_form_submission_callback(){
$data = $_POST;
$html = $_POST['message'];
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail("toemail#gmail.com", "Some subject", $html, $headers);
}
This way you can get ajax data and pass html wp_mail() function.
Check this link for whole demo : https://dev.to/shwetadanej/ajax-calls-in-wordpress-front-end-2g09
I am trying to send email in PHP using AJAX in a simple contact form. I have the following codes for a simple form, PHP code for submit button and AJAX script.
When I am trying to send email it is not sending any email and always firing the AJAX error msg. I am not very well in AJAX integration with PHP.
Below is my code
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
I would move the php part to another file:
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
And in another email.php
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
You must be stop the default flow of that form by using event.preventDefault(); and you can pass the form as multipart/formdata or form-data and check the developer tools -> network -> fetch/xhr -> payload/ formdata. then you create a seperate page in php and do the mail process in that page and change the form action link to that page
In html
<form method="post" class="myform" action="mail.php">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).on('submit', '.myform', function(e){
e.preventDefault();
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: new FormData($(".myform")[0]),
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
if (result.status == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
</script>
In php - mail.php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
if($send_email)
{
$response = ['status' => 'success'];
}
else
{
$response = ['status' => 'error'];
}
echo json_encode($response);
}
So, the top answer works, but as #Mithu said, for some reason it always says:
'Error Sending email!'
After 30 minutes of exploring the situation I understood that for some reason it returns from PHP not 'success' but ' success' with 2-4 spaces in front of the word 'success' or 'error'.
So, all you need is to exclude these spaces, for that we need to change 'succes' to 'this is success' and 'error' to 'this is error'(just to make spare letters in the front) and then we need to divide this string to words and to extract the last word. It will always be 'success' or 'error' regardless how much spaces the script will add or how much letters it will remove accidentally. And also you need to make another if else statement in the PHP to check FALSE instead of TRUE.
Also I've added a few lines which check if the fields are filled or not. And if they are not filled then you get a message 'Please fill in the forms.'.
So here how it looks and works for me:
Importing jquery library (you need to place it into the header):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
HTML (you need to put it there where you want to have the contact form):
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
JS (you need to put it in the footer):
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
// if it can't find email.php just chahge the url path to the full path, including your domain and all folders.
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
let d = result.split(" ");
let y = d.slice(-1)[0];
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
if (y == 'success'){
$('.output_message').text('Message Sent!');
}
else if (y == 'miss'){
$('.output_message').text('Please fill in all the fields above.');
}
else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
email.php (you need to create this file in the same folder where you have your index.php):
<?php
// here we check if all fields are filled.
$required = array('name', 'email', 'message');
$error = false;
foreach($required as $field) {
if (empty($_REQUEST[$field])) {
$error = true;
}
}
//if something is not filled(empty) and error is true
if ($error) {
echo 'this is miss';
}
// if everything is filled then we execute the mail function
else {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$fullmessage = "Sender's name: ".$name."\n"."Message: \n".$message;
// Set your email address where you want to receive emails.
$to = 'contact#yourdomain.com';
$subject = 'Message from YOUR E-MAIL.COM';
$send_email = mail($to,$subject,$fullmessage,$email);
if ($send_email == false) {
echo 'this is error';
} else {
echo 'this is success';
}
}
?>
So,this code steadily works for me, but maybe it is not very proffessionaly made, because I am a begginer in JS and PHP.
I have a contact form php+jquery+HTML.the form div is hidden in index.HTML,until contact button is presses.Jquery works,Ajax call posts needed data to php,which echoes a response.The problem is when php echoes,instead of remaining on same page without refreshing,browser redirects to contact.php,where the echo is showed correctly.I think the Ajax part won't catch the response from server,although syntax is the same in all tutorials.please assist.
html part:
HTML
<div id = 'contact_form'>
<div id = 'result'></div>
<form id="contactform" action="js/contact.php" method="POST" enctype="multipart/form-data">
<div class="row">
<input id="name" class="input" name="name" type="text" required = 'true' value="" size="30" placeholder='Nome'/>
</div>
<div class="row">
<input id="email" class="input" name="email" type="text" required = 'true' value="" size="30" placeholder = 'Email'/>
</div>
<div class="row">
<textarea id="message" class="input" name="message" rows="7" cols="50" required = 'true' placeholder = 'Messagio'></textarea>
</div>
<input id="submit_button" class = 'myButton' type="submit" value="Manda messagio" />
</form>
</div>
</div>
JS
$('#submit_btn').click(function(){
var user_name = $("input#name").val();
if (user_name == "") {
$("input#name").focus().addClass('active');
return false;
}
var user_email = $("input#email").val();
if (!$("input#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("input#email").focus().addClass('active');
return false;
}
var msg = $("textarea#message").val();
if (message == "") {
$("textarea#message").focus().addClass('active');
return false;
}
var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function(d) {
console.log(d);
}
});
return false;
});
PHP
<?php
$toEmail = "x#gmail.com";
$subject = "dal tuo sito ";
$mailHeaders = "From: " . $_POST["name"] . "<". $_POST["email"] .">\r\n";
if(mail($toEmail,$subject,$_POST["message"], $mailHeaders)) {
echo "Mail Sent";
} else {
echo "Problem in Sending Mail";
}
?>
If you want to keep the same button you can change your js.
$('#submit_btn').click(function(e){
e.preventDefault();
//YOUR CODE HERE
}
Because you used a submit type input, I recommend you change the submit input for a link like button. And also remove the action attr from the form:
HTML
Send
JS
<script>
$('#btn').on("click", function(){
//Your ajax here
//var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: {name: user_name, email: user_email, message: msg}
}).done(function(response){
console.log(response);
});
});
</script>
I have tried everything to get this form to work but no luck.
I guess abide is working now but my php is not sending the email. I don't even think that my php is getting called anyway.
my code is below
form code
line 434
<form id="myForm" data-abide action="mail.php" method="post">
<div class="contactform">
<div class="item item-pair">
<label for="name">Full Name
<input type="text" name="name" id="name" class="small-input cat_textbox" required pattern="[a-zA-Z]+" maxlength="255">
<small class="error small-input">Name is required and must be a string.</small>
</label>
<label for="email">Email Address
<input type="text" name="email" id="email" class="small-input cat_textbox" maxlength="255" required >
<small class="error small-input">An email address is required.</small>
</label>
</div>
<div class="item">
<label>Comments</label>
<textarea cols="10" name="message" id="message" rows="4" class="cat_listbox" required ></textarea>
<small class="error">Please enter your comments</small>
</div>
<div class="item">
<input class="button alert small" type="submit" value="Submit" id="catwebformbutton">
</div>
</div>
</form>
javascript code
line 627
<script>
$('#myForm').submit(function(e) {
//prevent default form submitting.
e.preventDefault();
$(this).on('valid', function() {
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for reponse
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"mail.php",
data: dataString,
success: function(data){
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<h2>Thanks!</h2>")
.append("<p>Dear "+ name +", I will get back to you as soon as I can ;)</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
});
</script>
html link
http://tayrani.com
Please help
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["message"];
$msg = "
Name:$name
Email:$email
Comment:
$comments";
$to = "tayrani#hotmail.com";
$subject = "website email";
$message = $msg;
$headers = "form";
mail($to,$subject,$message,$headers);
?>
Thanks for the help I got it working. It turned out to be Hotmail that is not accepting emails for some reason. So, I replaced the Hotmail account with a Gmail account and it worked. I also updated my code with the following
html code for the form
<form id="myForm" data-abide="ajax" action="mail.php" method="post">
<div class="contactform">
<div class="item item-pair">
<label for="name">Full Name
<input type="text" name="name" id="name" class="small-input cat_textbox" required pattern="[a-zA-Z]+" maxlength="255">
<small class="error small-input">Name is required and must be a string.</small>
</label>
<label for="email">Email Address
<input type="email" name="email" id="email" class="small-input cat_textbox" maxlength="255" required >
<small class="error small-input">An email address is required.</small>
</label>
</div>
<div class="item">
<label>Comments</label>
<textarea cols="10" name="message" id="message" rows="4" class="cat_listbox" required ></textarea>
<small class="error">Please enter your comments</small>
</div>
<div class="item">
<input class="button alert small" type="submit" value="Submit" id="catwebformbutton" name="btnSubmit">
</div>
</div>
</form>
My javascript code including fixing the submitting twice issue
<script>
$('#myForm').submit(function(e) {
//prevent default form submitting so it can run the ajax code first
e.preventDefault();
$(this).on('valid', function() { //if the form is valid then grab the values of these IDs (name, email, message)
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for reponse (store the values here)
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"mail.php", //runs the php code
data: dataString, //stores the data to be passed
success: function(data){ // if success then generate the div and append the the following
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<br /><h4>Thanks!</h4>")
.append('<p><span style="font-size:1.5em;">Hey</span> <span class="fancy">'+ name +'</span>,<br />I´ll get back to you as soon as I can ;)</p>')
.hide()
.fadeIn(1500);
},
error: function(jqXHR, status, error){ //this is to check if there is any error
alert("status: " + status + " message: " + error);
}
}); //End Ajax call
//return false;
});
});
</script>
<script>
$(document).foundation('abide', 'events'); // this was originally before the above code, but that makes the javascript code runs twice before submitting. Moved after and that fixes it.
</script>
Here is the php code
<?php
if(isset($_POST["name"])){
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["message"];
$msg = "
Name: $name
Email: $email
Comments:
$comments";
$to = "h2hussein#gmail.com";
$subject = "Tayrani.com Contact Form";
$headers = "From: <$email>";
mail($to,$subject,$msg,$headers);
}else{
}
?>
I struggled for 3 days to get this done but thanks to my colleague/friend Adam as he really helped me with it.
I hope this is useful for other people.
Thanks,
Hussein
tayrani.com
I'm making a ajax call to a server side function to send an email. It works fine. My issue is before sending the email i need to validate the captcha where the server side code resides in CaptchaValidation.php. If i call "CaptchaValidation.php" on form action it should work fine but here since i'm doing a ajax call i need to use e.preventDefault();. So that form action is not working.
How can i make it work?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divLoading').hide();
$('#appointment').submit(function (e) {
e.preventDefault();
var serviceURL = 'WebService.asmx/SendMail';
var Name = $("#fname").val();
var Email = $("#email").val();
var Telephone = $("#phone").val();
var Comment = $("#comment").val();
if ($("#fname").val().length == 0) {
alert("Please Enter Name");
$("#fname").focus();
return false;
}
if ($("#email").val().length == 0) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf("#") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf(".") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
$('#divLoading').show();
$.ajax({
type: "POST",
url: serviceURL,
data: '{"name":"' + Name + '","address":"' + Email + '","telephone":"' + Telephone + '","comment":"' + Comment + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
// alert("Mail Sent!");
$('#divLoading').hide();
window.location = "contat-submit.php";
}
function errorFunc() {
// alert('error');
}
});
});
</script>
</head>
<body>
<form name="appointment" id="appointment" method="post" action="CaptchaValidation.php">
<div>
</div><div id="leftcolumn4"><div class="h2">Contact Form</div>
<form name="appointment" id="Form1" method="post" action="send_contact.php">
Full Name:
<br />
<label>
<input name="fname" type="text" class="form-input" id="fname" size="30" />
</label>
<br /><br />
Email Address:<br />
<label>
<input name="email" type="text" class="form-input" id="email" size="30" />
</label><br /><br />
Telephone:
<br />
<label>
<input name="phone" type="text" class="form-input" id="phone" size="30" />
</label>
<br /><br />
Your Comment:<br />
<label>
<textarea name="comment" cols="28" rows="4" class="form-input-box" id="comment"></textarea><br />
<br />
</label><input name="submit" type="submit" class="form-input-submit" value="Submit" id="btnMail"/>
</div>
</form>
</body>
</html>
Follow the steps:
Change the Submit button to a simple button so that on click of that button the form will not submit.
On Click of that button call a function which will have call e.preventDefault();
function callSubmit() {
// do ajax call
}
You are doing ajax call in e.preventDefault() function. So in AJAX response, you have to check if the AJAX response is correct then do a form submit using:
$('#appointment').submit()
Now just remove the e.preventDefault(); function from you form.submit function you have written. This will allow to AJAX submit and send email.