I'm having trouble sending emails using ajax and recaptcha. I'm using 2 different files, my contact form and ajax code is on the index.html and the php code to validade the recaptcha and send the email is the email.php.
This is my ajax code, it is inside the body tag at the bottom of the page
<script>
$(".contact-card").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email)){
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000).delay(3000).fadeOut(1000);
}
});
} else{
$('.error').fadeIn(1000).delay(3000).fadeOut(1000);
}
return false;
});
</script>
and this is my php file called email.php
<?php
error_reporting(0);
if(isset($_POST['submit'])){
$to = "EMAIL";
$subject = "test";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$msgBody = 'Name: ' .$name. ' Message: ' .$message;
$headers = 'From: ' .$email;
$secretKey = "";
$responseKey = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if($response -> success){
if( mail($to, $subject, $msgBody, $headers)){
echo ("Success");
} else{
echo ("failed");
var_dump($_POST);
}
} else{
echo ("verification failed");
}
}
?>
I'm not using action on my form in the html.
Please help!!!
thank you!!
Related
I have a problem with reloading the page. After clicking submit form the page reloads. I click send the form and takes me to http: // localhost: 3000 / mail.php. And I would like the site not to be reloaded. (I use the validation form jquery plugin).This is my code:
jquery
(function(){
$("#contactForm").on('submit', function(e) {
e.preventDefault();
var data = {
name = $('#field-name').val(),
phone = $('#field-phone').val(),
email = $('#field-email').val(),
message = $('#field-message').val()
};
$.ajax({
type: "POST",
url: "mail.php",
data: data,
success: function(){
console.log("jej");
}
});
return false;
});
});
and php code
<?php
$to = 'name#gmail.com';
$name = $_POST['name'];
$phone = $_POST['phone'];
$email= $_POST['email'];
$text = $_POST['message'];
$subject = 'Nowy e-mail od ' . $name . ' (' . $email . ')';
$message = $name . $phone . $email . $text;
$headers = 'From: ' . $name . "\r\n" .
if(mail($to, $subject, $message, $headers)) {
print "<p class='success'>Mail Sent.</p>";
} else {
print "<p class='Error'>Problem in Sending Mail.</p>";
}
?>
change part of your code
$("#contactForm").on('submit', function(e)
to this...
$("#contactFormButton").on('click', function(e)
and change your submit button to this...
<button id="contactFormButton" type="button" class="form-control">Submit</button>
and here your php code...
if(mail($to, $subject, $message, $headers)) {
echo "Mail Sent!";
} else {
echo "Error!!";
}
and here you can catch result of your php code...
success: function(data){
console.log(data);
}
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!
Email form not sending and can't figure out why. I used the advice form this post tp create the form. Submit form and a textarea on ajax post
the reason for doing this is to greate a IE8 and 9 friendly form that works.
The on click function....
$("form#example-advanced-form").click(function() {
//alert("submitting?");
// validate() just checks that required fields have values
//if (validate()) {
$.ajax({
type: 'POST',
url: 'PHPMailer/sendMyform.php',
data: { name: $('#name').val(),
from: $('#email').val(),
subject: $('#role').val(),
message: $('#coverletter').val()
},// end data
success: function clearFields() {
$('#name').val('');
$('#email').val('');
} // end success
}); // end ajax
/*}
else
{
var errmsg = "Your email could not be sent.<br />";
errmsg += "Please ensure that you've filled in all the fields.";
$(".errmsg").html(errmsg);
$(".errmsg").css("color", "#ff0000");
}*/
$('form#example-advanced-form').submit();
}); // end click
The send mail form receiving the data...
error_reporting(E_ALL);
require_once("class.phpmailer.php");
include("class.smtp.php");
$email = new PHPMailer();
try
{
//
// Set server details for send
//
$email->IsSMTP();
$email->Host = "****";
$email->Port = 25;
$email->SMTPAuth = true;
$email->Username = "****";
$email->Password = "****";
//
// Send mail from the contact form
//
$to = "****";
$from = $_POST["email"];
$name = $_POST["name"];
$subject = "From web: ".$_POST["role"];
$message = $_POST["name"];
$body = "<p>Hi,</p>";
$body .= "<p>You have received a new query on your website.</p><p>Please see below:</p>";
$body .= "<p>";
$body .= str_replace("\r\n", "<br />", $message);
$body .= "</p>";
$body .= "</body></html>";
$email->SetFrom($from, $name);
$email->AddReplyTo($from, $name);
$email->AddAddress($to, $to);
$email->Subject = $subject;
$email->Body = $body;
$email->IsHTML(true);
$email->Send();
session_start();
$_SESSION["mailresult"] = "success";
http_redirect("http://www.this.com");
}
catch (Exception $e)
{
$_SESSION["mailresult"] = "failed";
$_SESSION["mailerror"] = $e->getMessage();
}
I get a error Call to undefined function on line 49 which is...
http_redirect("http://www.this.com");
I got the messege to apear in the DIV tag but not sure how to send the email address onto the external email database //myguestlist.com/mgl/formreceiver.php.
here is the HTML
Be the first to know about the Channel Seven Brisbane Racing
Carnival:
method="post" id="mf528c0a39d76be"> <input class="mailchimp-input"
input="" name="PatronEmail" id="mf528c0a39d76be_PatronEmail"
placeholder="Enter your email..." type="text"> <button type="submit"
class="btn"><span class="singup-image"><img src="img/send.png"
alt="send email"></span><span class="singup-text">Send</span></button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
Here is the PHP:
<?php
// Email address verification
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]]).)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]).){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'wbriton#brc.com.au';
$subscriber_email = ($_POST['PatronEmail']);
if(!isEmail($subscriber_Email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
//$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body);
}
}
?>
And here is the Java Script
$('.success-message').hide();
$('.error-message').hide();
$('.subscribe form').submit(function() {
var postdata = $('.subscribe form').serialize();
$.ajax({
type: 'POST',
url: 'php/sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
return false;
});
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;
}