I'm having a hard time with this reCAPTCHA integration.
Here's my code so far:
HTML
<div class="form_contact">
<form id="form1" name="form1" method="post" action="#">
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" placeholder="*Required Field" />
</div>
<div>
<label for="name">E-mail address:</label>
<input type="email" name="email" id="email" value="" tabindex="2" placeholder="*Required Field" />
</div>
<div>
<label for="name">Message Subject:</label>
<input type="text" name="msgTitle" id="msgTitle" value="" tabindex="3" placeholder="*Required Field" />
</div>
<div>
<label for="textarea">Message:</label>
<textarea cols="40" rows="8" name="message" id="message" tabindex="4" placeholder="*Required Field"></textarea>
</div>
<div>
<label for="textarea">Spam Blocker:</label>
<div class="captcha">
<?php
require_once('recaptchalib.php');
$publickey = "**********************************";
echo recaptcha_get_html($publickey);
?>
</div>
<a class="myButton" tabindex="5" id="submit" name="submit" href="#"> Submit <i class="fa fa-chevron-circle-right fa-2x"></i></
</form>
</div>
JQuery
<script>
$(function(){
$('.myButton').click(function() {
var data= {
name: $("#name").val(),
email: $("#email").val(),
msgTitle: $("#msgTitle").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "mail.php",
data: data,
success: function(data){
console.log(data);
}
});
alert('Message Sent!');
return false;
});
});
</script>
MAIL.php
<?php
require_once('recaptchalib.php');
$privatekey = "*******************";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
$mailto = 'sample#example.com';
$nameField = $_POST['name'];
$emailField = $_POST['email'];
$emailSubject = $_POST['msgTitle'];
$messageField = $_POST['message'];
$body = <<<EOD
<br><hr><br>
Name: $nameField <br>
Email: $emailField <br>
Message: $messageField <br>
EOD;
$headers = "From: $emailField\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
echo 'message sent!';
}
?>
I just want to display the error message below of the <form> if the reCAPTCHA inputs are incorrect.
Thanks in advance.!
Looks like a jQuery question, you can create a placeholder below the form to push in all the errors:
</form>
<div id="errors"></div>
And in your AJAX success call do:
success: function(data){
//clean it in case of multiple attempts
$('#errors').html(data);
}
.html() pastes the data sent from the server.
From the answer above I just wanna add this code if you want to return a callback from your backend
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
then you may want to change die into echo like so:
echo "The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"reCAPTCHA said: " . $resp->error . "";
then it should be like:
$.ajax({
type: "POST",
url: "mail.php",
data: data,
success: function(data){
$('#errors').html(data)
}
});
Related
I'm using g-Recaptcha v3 to pass a hidden token and HTML "Contact" form data to form.php file on the localhost, which verifies the g-Recaptcha data, returns a default prompt to end-user and sends an email, via the localhost to the default email address.
The email received does not display data captured, via the HTML "Contact" form. I have tried changing the syntax, I have tried additional "If/Else" statements as well as adding "POST" commands without any success.
HTML contact form section:
<!-- The Contact Section -->
<div class="w3-container w3-content w3-center w3-blue-gray w3-padding-64" style="max-width:1400px" id="contact">
<div class=" w3-container w3-content w3-center" style="max-width:1000px">
<h2 class="w3-wide">Contact</h2>
<p class="w3-opacity"><i>~ Lets Talk About Your Current Needs ~</i></p>
<form id="comment_form" action="form.php " method="post" target="_blank" >
<input class="w3-input w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your First Name: ex. Mark (with no spaces, punctuations or symbols)" name="fname" maxlength="32" pattern="[A-Za-z]{1,32}" required><br>
<input class="w3-input w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your Last Name: ex. Wilson (with no spaces, punctuations or symbols)" name="lname" maxlength="32" pattern="[A-Za-z]{1,32}" required>
<input class="w3-input w3-section w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your Email: ex. yourname#domainname.com" name="email" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" required>
<input class="w3-input w3-section w3-border w3-text-gray w3-center" placeholder="Enter Your Phone Number: ex.(112)112-1112 or 1121121112" name="phone" pattern="^(\s*)?(\+)?([- _():=+]?\d[- _():=+]?){10,14}(\s*)?$" required>
<textarea class="w3-input w3-section w3-border w3-text-gray w3-center" placeholder="Please Place Your Comment Here" name="comment" rows="5" required></textarea>
<i class="fa fa-paper-plane-o"></i>
<input type="submit" name="submit" value="SEND MESSAGE" class="w3-text-black"><br><br>
</form>
<script>
// when form is submit
$('#comment_form').submit(function() {
// we stopped it
event.preventDefault();
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var phone = $('#phone').val();
var comment = $("#comment").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('----------My Public Key----------', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{fname: fname, lname: lname, email: email, phone: phone, comment: comment, token: token}, function(result) {
console.log(result);
if(result.success) {
alert('Thanks for posting your comment!')
} else {
alert('Spammed Message - This Process Will Be Terminated')
}
});
});;
});
});
</script>
form.php
<?php
$fname;$lname;$email;$phone;$comment;$captcha;
if(isset($_POST['fname'])){
$fname=$_POST['fname'];
}if(isset($_POST['lname'])){
$lname=$_POST['lname'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['phone'])){
$phone=$_POST['phone'];
}if(isset($_POST['comment'])){
$comment=$_POST['comment'];
}if(isset($_POST['token'])){
$captcha=$_POST['token'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "--------------My Secret Key-----------------";
$ip = $_SERVER['REMOTE_ADDR'];
// POST REQUEST TO SERVER
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
header('Content-type: application/json');
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
} else {
echo json_encode(array('success' => 'false'));
}
// COLLECT CONTACT FORM DATA
$email = $_POST['email'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$number = $_POST['phone'];
$comment = $_POST['comment'];
// FORMAT EMAIL
$to = "default#emailaddress.com";
$headers = "From: {$to} \r\n";
$headers .= "Reply-To: {$email } \r\n";
$subject = "New form submission ... \r\n";
$body = "First Name: {$fname} \r\n";
$body .= "Last Name: {$lname} \r\n";
$body .= "Email: {$email} \r\n";
$body .= "Phone: {$phone } \r\n";
$body .= "Comment: {$comment}";
// SEND EMAIL to DEFAULT RECIPIENT VIA LOCALHOST
$send = mail($to, $subject, $body, $headers);
?>
HTML contact form:
Google g-recaptcha v3 verification prompt:
Email, via contact form, with missing data:
Im getting success from Ajax but not receiving the intended email and there does not seem to be anything wrong with the PHP. I have little experience with PHP, I need some way to get some feedback from the PHP.
Jquery
function PHP_EMAIL(name, email, message){
var emailInfo = [name,email,message];
$.ajax ({
type: "POST",
url:"the_php_file.php",
data: {email_info_array: emailInfo},
success: function(data) {
alert(data); <---alerts the entire php script back
alert("Email was successfuly sent!); <<<--- alerts success!
but no email recieved
}
});
}
PHP
$email_info = json_decode($_POST['email_info_array']);
$to = "my_email#gmail.com";
$subject = 'portfolio contact';
$user_name = $email_info[0];
$user_email = $email_info[1];
$message = $email_info[2];
$headers = "From: website.com";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
if(mail($to,$subject,$message,$headers))
{
echo "sent";
}
else
{
echo "fail";
}
HTML
<div class="site-contact-box site-text-20 site-text-grey-violet">
<!-- form -->
<form onsubmit="return false" id="emailform">
<div class="site-form-error">* You must fill all fields of the form *</div>
<br> Name <input type="text" name="name" value="" required> <div class="site-name-error site-text-12"> * invalid name </div>
<br> E-mail <input type="text" name="email" value="john.doe#example.com" required> <div class="site-email-error site-text-12"> * invalid email </div>
<br>
<div class="site-message-error site-text-12"> * message must be more than (8 characters) </div>
<br> <br> please leave a message...
<br> <p class="site-text-12"> (minimum 8 characters) <p>
<br>
<textarea rows="12" cols="50" name="message" form="emailform" required></textarea>
<br>
<div class="site-agree-error site-text-12"> you must agree to terms </div>
<br> <br>
<div class="site-agreement site-text-13 site-text-black">
* I agree to the Terms & Agreement <input type="checkbox" id="agree" required>
</div>
<br>
<input class="site-text-bold site-text-15" type="submit" name="submit" onclick="checkInput()">
</form>
</div>
<?php
header('Content-type: application/json');
echo json_encode($response_array);?>
query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Please help me with decoding what the real issue is. The issue is that I keep getting a blank email, despite all my tweaking and research on this code. Below are my html, javascript (ajax) and php code.
HTML code: file named contact.html
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
AJAX code:file named main.js
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
PHP code: file named sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
with this I keep on getting a blank email as depicted below
Name:
Email: Blank
Phone: Blank
Subject: Blank
Message: Blank
Have you tried with-out the die() at the end of your script? I think you might be killing your page too fast.
Also try creating a catch like this :
if (!mail(...))
{
// Reschedule for later try or panic appropriately!
}
Furthermore, you are suppressing warnings with # before mail();
Try removing the #.
Edit : Also, try removing the trims.
You have not set data while calling ajax, may be this is your problem.
When I test your code then I see that there fires a GET-request although you define the mehtod as POST in the form attribute. (Maybe that´s why jQuery use GET as default...). So the $_POST['name'] is empty because the parameter is in $_GET['name'].
And I can´t see the request parameters when I´m submiting the form. (Maybe that´s why the 'data' property is not set..)
Please try to complete the $.ajax with these:
method: 'POST'
data: $(this).serialize()
A BIG THANKS to ALL of you guys(#Mateusz Klimentowicz,#Mat VP,#Jose Manuel Abarca Rodríguez ,# Vladimir Nu). I actually followed your instructions and ended up correcting both the JS file and the PHP file as shown below:
JS file:
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
While the PHP code became this below:
<?php
$status = array(
'type'=>'success',
'message'=>'Thank you for contacting us. As soon as possible we will contact you!'
);
$fail = array(
'type'=>'fail',
'message'=>'Please try again. Your mail could not be delivered!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#mail.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
header('Content-type: application/json');
if($success){
echo json_encode($status);
}
else{
echo json_encode($fail);
}
?>
And after using this code as stated below, i end up not getting any blank page email. Email is now delievered with it's content. Thanks a bunch.
Sounds like an odd question but here is what I have. The php has a snippet at the end that says success or failure makes a white screen to display this, I really want it to pop up right under the submit button on the same page rather than redirect the entire page.
I assume I could direct that to an empty <div>?
mail.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent=" From: $name \n Phone: $phone \n Message: $message";
$recipient = "art#jamisonsigns.com";
$subject = "Web Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
?>
With a simple HTML form on my website as follows:
<form class="contact-form" form action="mail.php" method="POST">
<fieldset>
<input type="text" class="name" id="name" placeholder="Name...">
</fieldset>
<fieldset>
<input type="email" class="email" id="email" placeholder="Email...">
</fieldset>
<fieldset>
<input type="text" class="phone" id="phone" placeholder="Phone...">
</fieldset>
<fieldset>
<textarea name="message" id="message" cols="30" rows="4" placeholder="Message.."></textarea>
</fieldset>
<fieldset>
<input type="submit" class="button" id="button" value="Send Message">
</fieldset>
</form>
You need to submit the form with Ajax. Then on success insert the message in the html.
$('#button').click(function(event) {
event.preventDefault();
var formdata = $('#formID').serializeArray();
var url = '/urltopost.php';
$.ajax(
{
url : url,
type: "POST",
data: formdata,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
console.log("STATUS:" + textStatus + " | jqXHR:" + jqXHR + " | data:" + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR:" + " -> " +errorThrown);
}
});
});
Here it is a tutorial if you need..
Very new to this so apologies is my question is basic but it's stumped me for some hours.
I have a contact form which uses a bit of AJAX to POST to my PHP file. The problem im having is that when i try to get the PHP to email that data to myself, it isn't reading the POST values. The PHP was working when i tested it without the JS/AJAX post method, but in order to stop the page refresh I have gone with the AJAX option. Now that i've added the ajax in, the email result isn't showing up with the data (I can inspect and see that the Form Data is filled, just unclear why it isnt populating in the email) :
Name:
Email:
Message:
Any guidance as to why my mail server only receives the text but not the POST
Opening & Closing HTML on form:
<form data-parsley-validate action="./assets/contactform.php" method="POST">
<div class="formRow">
<label for="name" class="obscure">Name</label>
<input type="text" name="nameInput" id="name" placeholder="Name" required data-parsley-error-message="Please enter your name"></input>
</div>
<div class="formRow">
<label for="email" class="obscure">Email</label>
<input name="emailInput" id="email" type="email" placeholder="Email" required data-parsley-error-message="Please enter a valid email address"></input>
</div>
<div class="formRow">
<label for="message" class="obscure">Message</label>
<textarea name="messageInput" id="message">Message</textarea>
</div>
<input type="submit" name="submit"></input>
PHP Script:
<?php
$to = 'hello#kymlangford.com';
$subject = 'Post from your website';
$message = "Name: " . $_POST['nameInput'] . "\n Email: " . $_POST['emailInput'] . "\n Message: " . $_POST['messageInput'];
$headers = 'From: hello#kymlangford.com' . "\r\n" .
'Reply-To: ' . $_POST['emailInput'] . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
exit;
?>
Java for the form:
$(function() {
$.ajax({
type: 'POST',
url: './assets/contactform.php',
data: { name : $('input[name=nameInput]').val(),
email : $('input[name=emailInput]').val(),
message : $('textarea[name=messageInput]').val()
},
dataType: 'json'
})
event.preventDefault();
});
});
--Update 08/07/2014--
Below is the jquery code that solved my problem
// get the data from the form
$('form').submit(function(event){
var fdata = $(this).serializeArray();
fdata.push({ name: 'submit', value: true });
$.post('./assets/contactform.php', fdata, function (data) {
alert('Data Loaded:' + data); });
console.log(fdata);
event.preventDefault();
});
});
I think you can use jquery which is the same like ajax.
Here is the HTML code
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("sendemail.php", $("#contactform").serialize(), function(response)
{
$('#message').html(response);
});
return false;
});
});
</script>
</head>
<body>
<p>
<form action="" method="post" id="contactform" >
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="emailcontent">Email Content:</label><br />
<textarea name="emailcontent" id="emailcontent"></textarea><br />
<input type="button" value="Send Email" id="submit" /><div id="message"> </div>
</form>
</p>
</body>
</html>
Here is the PHP code, save it with 'sendemail.php' filename
$name = $_POST['name'];
$email = $_POST['email'];
$emailcontent = $_POST['emailcontent'];
$to = 'youremail#domain.com';
$subject = 'the subject';
$emailcontent = 'FROM: '.$name.' Email: '.$email.'Content: '.$emailcontent;
$headers = 'From: youremail#domain.com' . "\r\n";
mail($to, $subject, $message, $headers);
echo "Your email was sent!";