ReCaptcha 2.0 With AJAX - javascript

I have managed to get ReCaptcha 2.0 working in my website. However, it's only working when I don't use AJAX and I let the form submit "naturally".
I want to submit the form with the captcha and alert the user with a success note without refreshing the page.
I tried the following code, but it seems like the server doesn't get the user response:
HTML:
<form class="form" action="javascript:void(0)" novalidate>
<!-- all the inputs... -->
<!-- captcha -->
<div class="input-group">
<div class="g-recaptcha" data-sitekey="6LdOPgYTAAAAAE3ltWQGar80KUavaR-JblgPZjDI"></div>
</div>
<div class="errors" id="errors" style="display: none"></div>
<div class="input-group">
<input type="button" value="Send" class="btn-default right" id="submit">
<div class="clear"></div>
</div>
</form>
JS:
$('#submit').click(function(e) {
console.log('clicked submit'); // --> works
var $errors = $('#errors'),
$status = $('#status'),
name = $('#name').val().replace(/<|>/g, ""), // prevent xss
email = $('#email').val().replace(/<|>/g, ""),
msg = $('#message').val().replace(/<|>/g, "");
if (name == '' || email == '' || msg == '') {
valid = false;
errors = "All fields are required.";
}
// pretty sure the problem is here
console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:
if (!errors) {
// hide the errors
$errors.slideUp();
// ajax to the php file to send the mail
$.ajax({
type: "POST",
url: "http://orenurbach.com/assets/sendmail.php",
data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
}).done(function(status) {
if (status == "ok") {
// slide down the "ok" message to the user
$status.text('Thanks! Your message has been sent, and I will contact you soon.');
$status.slideDown();
// clear the form fields
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
} else {
$errors.text(errors);
$errors.slideDown();
}
});
PHP:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = '';
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
echo 'captcha: '.$captcha;
if (!$captcha)
echo 'The captcha has not been checked.';
// handling the captcha and checking if it's ok
$secret = 'MY_SECRET';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
var_dump($response);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response['success'] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo 'ok';
} else {
echo 'not ok';
}
?>
The result in the PHP page:
captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok
Bottom line is, how can I get the input response manually without it automatically going with the rest of the POST data?

Ok, this was pretty silly.
I have done a couple of things wrong:
In the PHP file, all the strings had single quotes on them, and that caused problems.
Throughout the testing, I added multiple printings of things in the PHP file, thus the if (status == "ok") was never working. I did get the emails but did not get any conformation that I did and now I see why.
When I wanted to check what the PHP file was omitting, I simply went to it's address in the URL and always got an error. Even when the mails were sent. Now I understand that that is not the correct way of checking the logs.
Thanks to #Samurai who helped my figure out things.
Final PHP code:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
if (!$captcha)
echo "not ok";
// handling the captcha and checking if it's ok
$secret = "MY_SECRET";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response["success"] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo "ok";
} else {
echo "not ok";
}
?>

Related

HTML form to trigger both php and javascript when submitted

I have a simple html form with just a box for the user to enter their email address.
When the "submit" button is pressed I want the email address submitted to be:
(a) emailed to me
(b) automatically added to a Google form
I can do both of these individually. I can perform (a) using:
<form id="input-form" action="email.php" method="POST">
where "email.php" is:
<?php
mail('me#gmail.com', $_POST['email'], "Add to Mailing List");
header('Location: https://my_website.com/thanks.html');
?>
and I do (b) using:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#input-form').on('submit',function(){
var inputq1 = encodeURIComponent($('#email').val());
var q1ID = "entry.1047793221";
var baseURL = 'https://docs.google.com/forms/d/e/1FAIpFLSe7dz1sfyEigQF3QGkTfKCieaqb8OgXoGzLOZPmhn6TvjqFg/formResponse?';
var submitURL = (baseURL + q1ID + "=" + inputq1);
console.log(submitURL);
$(this)[0].action=submitURL;
$('#input-feedback').text('Thank You!');
location.replace("https://my_website.com/thanks.html")
});
</script>
When I comment out the javascript, the submitted information is emailed to me as desired and the user is directed to my "thank you" page. But when I include the javascript, now the email doesn't arrive, but the email address that they entered is instead added to the Google form. So the Google form works part works, but it seems to override the sending of the email to myself.
Additionally, when the javascript is included the user no longer is redirected to my "thank you" page. Instead they are just directed to the Google form thank you page:
How can I get both (a) and (b) to happen after submission please?
You can use ajax to to activate your email.php script:
<script>
$('#input-form').on('submit',function(e){
e.preventDefault(); // this stops the form submit
var inputq1 = encodeURIComponent($('#email').val());
var q1ID = "entry.1047793221";
var baseURL = 'https://docs.google.com/forms/d/e/1FAIpFLSe7dz1sfyEigQF3QGkTfKCieaqb8OgXoGzLOZPmhn6TvjqFg/formResponse?';
var submitURL = (baseURL + q1ID + "=" + inputq1);
console.log(submitURL);
$(this)[0].action=submitURL;
var data = {
// fill with form input values
email: $('#email').val(),
};
// send ajax request to send your email
$.ajax({
url: '/email.php',
type: 'POST',
data: data,
success: function( response ) {
response = JSON.parse( response );
// check if email is sent successfuly and respond appropriately
if (response.status == 'success') {
$('#input-feedback').text('Thank You!');
location.replace("https://my_website.com/thanks.html")
} else {
$('#input-feedback').text('Ooops! Something went wrong.');
}
},
error: function (xhr, status, error) {
console.log( xhr.responseText );
}
});
});
</script>
PHP
<?php
$response = [
'status' => 'error',
];
// validate input values
if (empty($_POST['email'])) { // this is the most basic validation
echo json_encode($response); exit();
}
// check if mail was sent successfuly
if( mail('me#gmail.com', $_POST['email'], "Add to Mailing List") ) {
$response['status'] = 'success';
echo json_encode($response); exit();
}
// if email failed to send
echo json_encode($response); exit();

Clear input fields after submitting AJAX to PHP

This is a password recovery form through HTML page that post data to PHP file via AJAX. Everything is okay with the code except once submitted and response recived, form input fields don't clear. I have been searching the web for the past 4 hours and found too many code lines to do so but none of them seems to work. plz help me in this matter :) have a good day.
$(function() {
/////////////////////////////////////////////////////////'Form ID' & 'Element Name' /////////////////////////////////////////
// Get the form.
var form = $('#emailform');
// Get the messages div.
var formMessages = $('#formresults');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
// $('#email1').val('');
//var email = $('input[name=#email]').val("");
//document.getElementById("emailform").reset();
//$('#emailform')[0].reset();
//$('input:text').val('');
//$('#emailform input[type=text]').val('');
//setTimeout(function(){
//$('input,textarea','#emailform').val(''); //clearing inputs
//},1);
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Contact Form Demo</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>AJAX Contact Form Demo</h1>
<div id="formresults"></div>
<form id="emailform" name="emailform1" method="post" action="exa.php">
<table align="center">
<tr><td><div class="input-append"><input type="text" name="email" id="email1" class="input-xlarge" placeholder="email" maxlength="100" /><span class="add-on"><li class="icon-envelope"></li></span></div></td></tr>
</table>
<!-- <hr /> -->
<center><input type="submit" name="Forget" id="btn" class="btn btn-primary Loading-btn" value="ٍSend" data-loading-text="Sending ..." /></center>
</form>
</div>
<script src="ajax/jquery-2.1.0.min.js"></script>
<script src="ajax/app.js"></script>
</body>
</html>
<?php
// Get Access to data base
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$email = $_POST["email"];
// Check that data was sent to the mailer.
if ( empty($email) ) {
// Set a 400 (bad request) response code and exit.
http_response_code(100);
echo "BLABLABLA.";
exit;
}
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
// Set a 400 (bad request) response code and exit.
http_response_code(200);
echo "BLABLABLA.";
exit;
}
if (#mysql_num_rows(mysql_query("SELECT `id` FROM `accounts` WHERE `email`='$email'")) < 1) {
// Set a 400 (bad request) response code and exit.
http_response_code(300);
echo "BLABLABLA.";
exit;
}
$row_user = #mysql_fetch_array(mysql_query("SELECT * FROM `accounts` WHERE `email`='$email'"));
////////////////////////////
$password = $row_user['pass'];
$to = $row_user['email'];
$subject = "Your Recovered Password";
$message = "Please use this password to login: " . $password;
$headers = "From : XXX#XXX.XXX";
// Send the email.
if (mail($to, $subject, $message, $headers)) {
// Set a 200 (okay) response code.
http_response_code(400);
echo "BLABLABLA.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "BLABLABLA.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(600);
echo "There was a problem with your submission, please try again.";
}
?>
You can use JavaScript's .reset() function on the form element which will clear all input fields.
I found the answer, just removed http_response_code()
for all if statments .
Thx all for your help. I can sleep now knowing my day is not wasted :)

Contact form using jquery, ajax, and mailer php script does nothing when clicking submit

I have a contact form on my website and I'm trying to implement send to email functionality when the user enters information and clicks submit. So, ideally the information in the contact form should be emailed to me after submit. What I'm trying to implement uses jQuery, AJAX, and a PHP mailer script I got from the tutorial located here: http://blog.teamtreehouse.com/create-ajax-contact-form
The problem is when I click Submit, nothing happens, nothing is redirected stating there is an error or telling me it's successful. Only thing to happen is the form fields are cleared. I read in the comments on that site a certain version of PHP is required for the mailer script, but I'm not too experienced with PHP and back-end development. I know something's missing, just not sure what. Seems like some communication is missing and I'm not getting any javascript errors. All of the id and name attributes match in my .html, .js and .php files. Files are also uploaded in Bluehost (currently where site is hosted). Do I need to install a new PHP version somewhere in Bluehost? Any help is appreciated. Thanks!
$(document).ready(function(e) {
//e.preventDefault();
$("button").click(function(e) {
var ajax = {
isSubmitting: false,
send: function() {
if(ajax.isSubmitting == false) {
ajax.isSubmitting = true;
var userName = $("input [name=contact-name]");
var userEmail = $("input [name=contact-email]");
var userWebsite = $("input [name=contact-website]");
var userMessage = $("input [name=contact-message]");
if(userName === "" || userEmail === "" || userWebsite === "" || userMessage === "") {
alert("Please fill out all required fields.");
}
else {
$.post("mailer3.php", {
name: userName,
email: userEmail,
website: userWebsite,
message: userMessage
}, function(data) {
ajax.isSubmitting = false;
});
}
}
else alert("Send only 1 email at a time.");
}
}
});
});
PHP
<?php
//PHP Mailer Script
if(count($_POST) > 0) {
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$message = $_POST['message'];
$header = "Content-Type: text/html\r\nReply-To:: $email\r\nFrom: $name <$email>";
$body =
#"Email sent from ".$_SERVER['REMOTE_ADDR']." at ".date("d/m/Y H:i",time())."<br />
<hr />
$message
<hr />
Email end";
if(mail("andrew#ajcwebcreations.com", "You have a new message.", $message, $header)) {
die("true");
} else {
die("Error sending message.");
}
}
?>
Andrew
Started over from scratch and got email to send, but input isn't included in the email only the subject. Maybe going to post another question for that issue if I can't figure it out. Thanks to all those who took the time to add input!

Validating Contact Form with Captcha

I have a contact form with a captha in it. There is no problem submitting mail, but the issue I have is validation and transferring the values to submit handler. I have limited knowledge of PHP and Javascript. I humbly seek your help in checking these codes and tell me what I need to do to get it right. Any help will be appreciated!
Below are the mail handler php codes
<?php
require_once('recaptchalib.php');
$publickey = "***********";
$subject = 'CONTACT MESSAGE: ' ; //. $_REQUEST['subject']Subject of your email
$to = 'myemailaddress#domain.com'; //Recipient's E-mail
$privatekey = "***********";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message .= 'Name: ' . $_REQUEST['name'] . "<br>";
$message .= 'Telephone: ' . $_REQUEST['telephone'] . "<br>";
$message .= 'Email: ' . $_REQUEST['email'] . "<br>";
$message .= 'Message: ' . $_REQUEST['message'];
if (#mail($to, $subject, $message, $headers))
{
// Transfer the value 'sent' to ajax function for showing success message.
echo 'sent';
}
else
{
// Transfer the value 'failed' to ajax function for showing error message.
echo 'failed';
}
} else {
echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->error;
}
?>
And here is the javascript
<script>
function validateForm() {
var x = document.forms["enquiries"]["name"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your full name", "error");
return false;
}
var x = document.forms["enquiries"]["email"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your a valid email address", "error");
return false;
}
var x = document.forms["enquiries"]["message"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your the message you wish to send", "error");
return false;
}
// If there is no validation error, next to process the mail function
if(error == false){
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("processContactEmail.php", $("#enquiries").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
sweetAlert("Congratulations", "Your message has been sent successfully!", "success");
}else{
//Display the error message
}
});
}
}
</script>
and finally, the html
<form name="enquiries" id='enquiries' method="post" action='processContactEmail.php' onSubmit="return validate();">
<label> <input name="name" type="text" id="name" style="width: 90%;" placeholder="Name" ></label>
<label><input name="email" type="text" id="email" style="width: 90%;" placeholder="Email"></label>
<label><textarea name="message" id="message" style="width: 96.5%;" class="mssg" rows="10" placeholder="Message"></textarea>
</label>
<label><?php echo recaptcha_get_html($publickey) ?></label>
<label><input name="submit" type='submit' id='mssg_buttton' value='Send Message'></label>
</form>
When I clicked on the submit button, I was taken straight to
processContactEmail.php page without the form validating
How do I display this error: echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->error; in my alert
I'm not sure about this line if(error == false){ in the JS script since there is no variable declared
The first problem looks like your validation function is referred to in your HTML as validate();
<form name="enquiries" id='enquiries' method="post" action='processContactEmail.php' onSubmit="return validate();">
But in your Javascript the function defined is called validateForm(). To fix that just make sure these are called the same thing (doesn't matter what, as long as they match).
Rather than calling the validation function inline with onSubmit="return validate();" , it's better to attach a separate event listener in the Javascript. It's good practice to separate your HTML and Javascript code. I see you're using JQuery, so you do this in your Javascript like so:
$( document ).ready(function() { // Make sure DOM is loaded before attaching the event listener to the form element
$("#enquiries").on("submit", validateForm); // Add submit listener to the form with the id 'enquiries' and run the function called validateForm on submit
});
Secondly, in your validate function, you need to prevent the form's default action of submitting and redirecting to the action processContactEmail.php. The HTML form will always try to post to its default action, so do make it do something else (like validate) you must actively stop it from posting.
You do this in JQuery by editing your validateForm function to prevent the form's default action with event.preventDefault. As for the error, you must first set an error variable to false (assume all is fine) and as you find errors, you change it to true. If it's still false after the checks, there were no errors.
Your Javascript function should look like this:
function validateForm(event) {
event.preventDefault(); // the variable "event" is automatically included in the submit event listener.
var error = false; // Assume it's fine unless proven otherwise
var x = document.forms["enquiries"]["name"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your full name", "error");
error = true; // The form is not fine. Set error to true.
// No return, or you will not get to the rest of your function
}
var x = document.forms["enquiries"]["email"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your a valid email address", "error");
error = true; // The form is not fine. Set error to true.
}
var x = document.forms["enquiries"]["message"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your the message you wish to send", "error");
error = true; // The form is not fine. Set error to true.
}
// If there is no validation error, next to process the mail function
if(error == false){ // error was never set to true, so it must still be false and the form is OK.
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php */
$.post("processContactEmail.php", $("#enquiries").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
sweetAlert("Congratulations", "Your message has been sent successfully!", "success");
} else {
//Display the error message
}
});
}
}
After these changes, your form will not post to its action, and your validateForm function should run, check for the errors, and if there are none, make the ajax POST to processContactEmail.php.

showing text in div without reloading the page

In the following code, I have a contact form and in that form there is an email validation script. As a result of validation, I want the error message to be shown in a div called confirmation without reloading the page. Also, if the email is valid, the mail will be sent and I want the Thank you message to be shown in the same div confirmation. The problem is what can I do to prevent reloading the page and let the error message or the thanks message shows in the confirmation div?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11#gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
Thanks
<input type="text" name="from" id ="from">
Call example:
var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});
request.done(function( msg ) {
//handle HTML
});
request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});
PHP Side
<?php
$email = $_POST["email"]
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}
echo spamcheck($email);
There's no way you could do that with just PHP.
What you're looking at is commonly known as AJAX, and uses client-side language (Javascript)
It's very common, and widely used on the internet. You can find many examples and production-ready scripts by searching ajax on google.
More informations here : http://www.w3schools.com/ajax/

Categories

Resources