Implemented reCaptcha... Still getting spam - javascript

I just implemented a reCaptcha on a WP Site contact form.
It works like this:
Submission is cancelled using $form.submit(function(e) { e.preventDefault(); return false; }
reCaptcha is dynamically inserted before the form.
if reCaptcha's AJAX response is successful, perform HTLMFormElement.submit, using $form[0].submit();
HTML
<div id="ny_cf-3" class="footer-ny widget widget_ny_cf"><h2 class="widgettitle">Contact Us</h2>
<!-- contact form widget -->
<p class="response"></p>
<form method="post" enctype="multipart/form-data" class="ny-footer-contact-form" action="http://wpstage.leadscon.com/leadsconny/" data-submit="return fm_submit_onclick(1)" id="fm-form-1" name="fm-form-1">
<div class="form-group" id="fm-item-text-53546749dea0d">
<input type="text" name="text-53546749dea0d" id="text-53546749dea0d" style="width:px;" placeholder="Your name" class="form-control">
</div>
<div class="form-group" id="fm-item-text-5354674e4b90b">
<input type="text" name="text-5354674e4b90b" id="text-5354674e4b90b" style="width:px;" placeholder="Email address" class="form-control">
</div>
<div class="form-group" id="fm-item-textarea-5354675009293">
<textarea name="textarea-5354675009293" id="textarea-5354675009293" style="width:px;height:100px;" placeholder="Your message" class="form-control"></textarea>
</div>
<input type="email" class="teddybear" style="display:none">
<button type="submit" id="fm_form_submit" name="fm_form_submit" class="btn btn-primary btn-block submit">Submit</button>
<input type="hidden" name="fm_nonce" id="fm_nonce" value="1165f15ac2">
<input type="hidden" name="fm_id" id="fm_id" value="1">
<input type="hidden" name="fm_uniq_id" id="fm_uniq_id" value="fm-536b89c742833">
<input type="hidden" name="fm_parent_post_id" id="fm_parent_post_id" value="4">
</form>
<!-- end cf widget -->
</div>
JavaScript code:
var getRecaptcha = function($form, $frmResponseField) {
$form.fadeOut();
// Add the reCaptcha
// ========================================================================
var $recaptchaForm = $('<form class="recaptcha_form" style="display:none;"><p><strong>Spam verification (sorry):</strong></p><p class="response"></p><button class="btn btn-success btn-sm" type="submit">Submit</button></form>');
var recaptcha_el = $('<div id="recaptcha_el"></div>').insertAfter($recaptchaForm.find('.response')).get(0);
$recaptchaForm.insertBefore($form).slideDown();
leadsCon.reCaptchaHTML().appendTo($(recaptcha_el));
Recaptcha.create('6LdUZPASAAAAAGZI_z-qQ7988o0nGouHHtIsh4yX', recaptcha_el, {
theme : 'custom',
custom_theme_widget: 'recaptcha_widget',
callback: Recaptcha.focus_response_field
});
// Bind submit action to check it
$recaptchaForm.submit(function(e) {
e.preventDefault();
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
var $btn = $recaptchaForm.find('button[type="submit"]')
var btnVal = $btn.html();
var $responseField = $recaptchaForm.find('.response');
var data = {
action: 'verify_recaptcha',
challenge: challenge,
response: response
};
$btn.html("<i class='dashicons dashicons-clock'></i>");
$responseField.text('');
$.post(ajax_object.ajax_url, data, function(response) {
if ( response.success == true ) {
$responseField.removeClass('text-danger').addClass('text-success').html('<i class="icon-ok"></i> You got it. One second...');
// We're ok.. send.
Recaptcha.destroy();
$recaptchaForm.remove();
$frmResponseField.removeClass('text-danger').addClass('text-success').html('<i class="icon-ok"></i> Wait while we send your message.');
$form[0].submit();
} else {
$responseField.removeClass('text-success').addClass('text-danger').html('<i class="dashicons dashicons-dismiss"></i> Oops! Try again.');
$btn.html(btnVal);
}
});
});
};
$('.ny-footer-contact-form').submit(function (e) {
e.preventDefault();
var $form = $(this);
var $responseField = $form.siblings('.response').removeClass('text-success text-danger').html('');
var command = $form.attr('data-submit').match(/return (\w+)\((.+)\)/i);
var fn = window[command[1]];
var $honeypot = $form.find('input.teddybear');
if ( fn(command[2]) && $honeypot.val() == '' ) {
getRecaptcha($form, $responseField);
} else {
$responseField.removeClass('text-success').addClass('text-danger').html('<i class="dashicons dashicons-dismiss"></i> There are missing fields.');
}
return false;
});
My impression is that since $form[0].submit() is not in any way filtered and doesn't trigger the submit event from jQuery, spammers are using that to submit the form and circunvent the reCaptcha.
What can I do?

A spammer will not execute your javascript code. They will simply post to the correct URL. Therefore you can't reliably validate anything on the client, you'll have to validate it on the server as well.

Bots can even does not run your JS - they just find forms in raw html and try to act as an user submitting the form. You have to validate reCaptcha value on server side, see here: https://developers.google.com/recaptcha/docs/php

Related

php not inserting data into table

I have a HTML form
<div class="contact-form col-md-6 " >
<form id="contact-form" method="post" action="" role="form">
<div class="form-group">
<input type="text" placeholder="Your Name" class="form-control" name="name" id="name" required>
</div>
<div class="form-group">
<input type="email" placeholder="Your Email" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<input type="text" placeholder="Your Phone Number" class="form-control" name="phone" id="phone" required>
</div>
<div class="response_msg"></div>
<div id="mail-success" class="success">
Thank you. You are registerd. :)
</div>
<div id="mail-fail" class="error">
Sorry, don't know what happened. Try later :(
</div>
<div id="cf-submit">
<input type="submit" id="contact-submit" class="btn btn-transparent" value="Register" name="submit">
</div>
</form>
</div>
I need to submit form on same page and show message on successfully submission. I am using JS for this
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
if($("#contact-form [name='name']").val() === '')
{
$("#contact-form [name='name']").css("border","1px solid red");
}
else if ($("#contact-form [name='email']").val() === '')
{
$("#contact-form [name='email']").css("border","1px solid red");
}
else if ($("#contact-form [name='phone']").val() === '')
{
$("#contact-form [name='phone']").css("border","1px solid red");
}
else
{
$("#loading-img").css("display","block");
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data){
$("#loading-img").css("display","none");
$(".response_msg").text(data);
$(".response_msg").slideDown().fadeOut(3000);
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
});
}
});
$("#contact-form input").blur(function(){
var checkValue = $(this).val();
if(checkValue != '')
{
$(this).css("border","1px solid #eeeeee");
}
});
});
</script>
As soon i clicked on submit button page refresh but my i don't see my pho code inserting data in database.
<?php
require_once("conn.php");
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
// require_once("contact_mail.php");
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$sql="INSERT INTO Beta_Registration (name, email, phone) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else
{
echo "Thank you! We will contact you soon";
}
}
else
{
echo "Please fill Name and Email";
}
?>
I want my form to submit on same page also stays on same block and shows the messages in div inside form when data entered successfully or failed into database.
The issues i am facing whenever i press submit button it refreshed the page and form data doesn't executed into database. It might be php or JS i am using. Please help me in this.
1- You need to add "return false" in your on submit function to prevent browser to submit the form
$(document).ready(function () {
$("#contact-form").on("submit", function (e) {
...
return false;
});
...
});
2- You need to match you database table name, and their columns name which you have used in your MySQL query.

Request payload mysteriously not set when submitting form second time: AngularJS

Desperately need another set of eyes. This form submission works perfectly on the first submission. But unless I reload the page again it fails. I feel like I've checked everything, the form values are reset fine no matter what in the js but for some reason they do not make it into the Request payload on the second post. Any help is much appreciated.
$scope.submitLogin = function(data) {
var form = $scope.login;
$scope.formerror = '';
$scope.success = '';
if (form.username.length > 0 &&
form.password.length > 0) {
console.log(form.username);
console.log(form.password);
$http.post('/login', form)
.success(function(data) {
$scope.success = data['res'];
$scope.login = [];
window.scrollTo(0, 0);
})
.error(function(data) {
$scope.formerror = data;
});
} else {
$scope.formerror = "something went wrong. Try again.";
}
//$scope.form = new Array({'error':'test', 'msg':''});
}
<form id="login-form" ng-submit="submitLogin()" role="form">
<label for="login_user">username: </label>
<input id="login_user" ng-model="login.username" type="text" name="username" class="form-control" placeholder="username">
<label for="login_password">password: </label>
<input id="login_password" ng-model="login.password" type="password" name="password" class="form-control" placeholder="password">
<input class="btn btn-primary" type="submit" class="btn btn-success btn-send" value="login">
</form>

HTML Form onsubmit not executing the external function

I have a HTML Form and on submit, a validate() function to be called.
The submit works fine, if the validate() function is within the "script" tag at the end of the "body" tag.
Otherwise, the submit doesn't call the validate() function when it is present in external js file, even though document.ready is used, as in https://jsfiddle.net/vg47127o/1/
HTML --
<form method="post" action="#" onsubmit="return validate()" name="loginForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="error-block"><span class="glyphicon glyphicon-exclamation-sign"> </span> <span class="error-msg"></span></p>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="username">username:
</label>
<div class="col-sm-9">
<input type="text" class="form-control digits-only" id="username" placeholder="Enter Username">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">Password:</label>
<div class="col-sm-9">
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" id="loginBtn" class="btn btn-default">Log In</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
SCRIPT --
$(document).ready(function() {
var displayError = function(error, msg) {
$(".error-block .error-msg").text(msg);
if (error === true)
$(".error-block").show();
else
$(".error-block").hide();
return true;
};
//Validating the input fields
var validate = function() {
var $username = $("#username").val(),
$password = $("#password").val();
if ($username === '' || $password === '') {
displayError(true, ' Username or Password cannot be empty. ');
return false;
} else if ($username.length < 6 || $password.length < 6) {
displayError(true, ' Username and Password should be a minimum of 6 characters. ');
return false;
} else {
displayError(false, ' ');
return true;
}
};
});
Am I missing out something here or What could be the reason for this.
Here's an updated fiddle that is working. You need to trap the submit() event if validate does not return true.
This is what you would include in your jQuery:
$("form").on("submit", function (event) {
if (!validate()) {
event.preventDefault();
}
});
Then your <form> tag would simply be <form method="post" action="#" name="loginForm" class="form-horizontal" role="form">
FYI
The reason for this is that when your validate() function is inside of your document ready, it is scoped to the document ready function, therefore, inline DOM event triggers do not have access to it. You have to set up the event handler inside the jQuery function, or declare your validate() function outside of your document ready function.
The validate variable is scoped to the anonymous function you put into $(document).ready. That means it can be accessed only from within that function and not from the page which lives in the global scope.
Add the event listener using the $(...).submit function instead:
$(document).ready(function() {
/* *** */
//Validating the input fields
$("[name=loginForm]").submit(function() {
var $username = $("#username").val(),
$password = $("#password").val();
/* *** */
});
});

Google App Script Closure error when calling script

This is my first foray into Google scripts and I have a form that calls two different Google app scripts(both are in the .gs file). One Uploads a file while the other saves the form data to a google spreadsheet. For some reason I get an error when calling the file upload script
(Uncaught TypeError: Cannot read property 'closure_lm_407634' of null)
While the script that uploads the data works fine.
Saving the form data to spreadsheet(which works):
google.script.run.withUserObject(data).saveToSheet(data);
-- which calls:
function saveToSheet(data) {
var date = new Date();
var sheet = SpreadsheetApp.openById(submissionSSKey);
sheet
.appendRow([date, data.name, data.email, data.headline,
data.location, data.newsContent, data.websiteContent, data.expiry, data.fileUrl]);
}
Uploading file(doesn't work):
google.script.run
.withUserObject(theForm)
.withSuccessHandler(processForm)
.uploadFile(theForm);
-- which calls:
function uploadFile(form) {
var folder = DriveApp.getFolderById(folderId), doc = '', file = form.uploadedFile;
if (file.getName()) { doc = folder.createFile(file); }
return doc;
}
I can't for the life of me figure out why one call works while the other does not. I've tried every way I could think of to call the upload script but nothing works. I've tried removing the user object and success handler.
HTML:
<?!= include('styles'); ?>
<div id="container" class="col-lg-12 col-md-12 col-sm-12">
<header class="col-lg-offset-3 col-md-offset-3"></header>
<div class="col-lg-offset-3 col-lg-6 col-md-6 col-sm-12" id="form">
<h1 class="text-center">
SAS News Submission
</h1>
<span id="required-content">
<sup>*</sup>
Required
</span>
<br>
<br>
<form name="sas-form">
<label for="name" class="required">Contact Person/ Source of News</label>
<input type="text" name="name" value="test" class="form-control" id="name" required="required">
<br>
<label for="email" class="required">Contact Person's email (in case we have questions regarding your News content)</label>
<input type="email" name="email" value="me#me.com" id="email" class="form-control" required="required">
<br>
<label for="headline" class="required">Headline (try to keep below 10 words if possible) </label>
<input type="text" name="headline" value="headline" id="headline" class="form-control" required="required">
<br>
<label for="newsContent" class="required">News Content *Note all content must be fully edited to ensure posting</label>
<textarea rows="5" cols="0" name="newsContent" class="form-control" id="newsContent" required="required">
Content
</textarea>
<br>
<label class="required">Where would you like the News to be shared? (You may choose more than one)</label>
<ul id="social-list">
<li>
<input type="checkbox" name="newsletter" id="newsletter" value="newsletter">
<label for="newsletter"> Newsletter</label>
</li>
<li>
<input type="checkbox" name="social" id="social" value="social">
<label for="social"> Social Media (Facebook, LinkedIn, Twitter)</label>
</li>
<li>
<input type="checkbox" name="website" id="website" value="website" checked>
<label for="website"> Website </label>
</li>
</ul>
<br>
<label for="websiteContent">If you chose the website, please provide specific instructions on where you would like the content to be posted.</label>
<br>
<small>News and Events Page, Volunteer Page, Student Page, etc. Ex: Please post in the News and Events Page and send the link and headline out on social media.</small>
<textarea rows="5" cols="0" name="websiteContent" id="websiteContent" class="form-control">website content</textarea>
<br>
<label for="expiry">If your content has an expiration date, please share that date below.</label>
<input type="date" name="expiry" id="expiry" class="form-control">
<br>
<label>If you have files that need to be attached, pick them below.</label>
<input type="file" name="uploadedFile" id="file">
<br>
<div id="not-valid"><span></span></div>
<div id="error"><span>
An error occurred, please try submitting again.
</span></div>
<div id="success"><span>
Form submission was successful! Thank you!
</span></div>
<input type="button" value="Submit" class="btn btn-primary" id="submit"
onclick="validateForm(this.parentNode)">
</form>
</div>
</div>
<footer>
<?!= include('javascript'); ?>
</footer>
<script>
var validateForm = function(theForm)
{
var valid = true;
$('#not-valid span').empty();
$('input').removeClass('warning');
if($('#name').val() == '')
{
$('#name').addClass('warning');
$('#not-valid span').append('Please enter a name <br>');
valid = false;
}
if($('#email').val() == '')
{
$('#email').addClass('warning');
$('#not-valid span').append('Please enter an email <br>');
valid = false;
}
if($('#headline').val() == '')
{
$('#headline').addClass('warning');
$('#not-valid span').append('Please enter a headline <br>');
valid = false;
}
if($('#newsContent').val() == '')
{
$('#newsContent').addClass('warning');
$('#not-valid span').append('Please enter news content <br>');
valid = false;
}
if(!$('#social').is(':checked') && !$('#website').is(':checked') && !$('#newsletter').is(':checked'))
{
$('#not-valid span').append('Please choose where you would like the news to be shared. <br>');
$('#social-list').addClass('warning');
valid = false;
}
if(valid)
{
google.script.run.withSuccessHandler(processForm).uploadFile(theForm)
}
};
function processForm(file)
{
var fileUrl = file ? file.getUrl() : 'No file uploaded',
location = [];
if($('#social').is(':checked'))
{
location.push('social');
}
if($('#newsletter').is(':checked'))
{
location.push('newletter');
}
if($('#website').is(':checked'))
{
location.push('website');
}
var data = {
name: $('#name').val(),
email: $('#email').val(),
headline: $('#headline').val(),
location: location.toString(),
newsContent: $('#newsContent').val(),
websiteContent: $('#websiteContent').val(),
expiry: $('#expiry').val() ? $('#expiry').val() : 'No expiration date selected',
fileUrl: fileUrl
};
google.script.run.saveToSheet(data);
clearForm();
success();
};
var clearForm = function()
{
$("input[type=text], input[type=date], textarea, input[type=email], input[type=file]").val("");
$("input[type=checkbox]").attr('checked', false);
enableSubmit();
};
var success = function()
{
$('#success').show()
};
var enableSubmit = function()
{
$("#submit").prop('disabled', false);
};
</script>
I was able to reproduce your error. I have no idea why that error is occurring, but I found a way to make it work.
Here is what you need to do:
Put an id attribute into the upper form tag:
<form id="myForm">
Remove the button using an input tag.
Add a <button> tag outside of the form. Must be outside of the form. And get the form with document.getElementById('myForm')
<form id="myForm">
<input type="file" name="uploadedFile">
</form>
<button onclick="validateForm(document.getElementById('myForm'))">submit</button>
I've tested this. It got the file, and sent it to the server inside of the form element.
You can use Logger.log() in the server code without using the debugger.
function uploadFile(form) {
Logger.log('form: ' + form);
Logger.log('form.uploadedFile: ' + form.uploadedFile);
Logger.log('form.uploadedFile: ' + form.uploadedFile.getName());

Angularjs email form field not clearing/resetting after model binding reset

Hey so I have a form which has three fields name,email and phone.
<div ng-show="Nerd.adding">
<form class="col-sm-6" name="Nerd.nerdAddFrm" novalidate >
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Name" ng-model="Nerd.nerd.name" required >
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Email" ng-model="Nerd.nerd.email" required >
</div>
<div class="form-group">
<label for="inputPhone">Phone</label>
<input type="text" class="form-control" id="inputPhone" placeholder="Phone" ng-model="Nerd.nerd.phone" required >
</div>
<button ng-click="Nerd.saveNerd(Nerd.nerd)" type="submit" class="btn btn-primary">Submit</button>
<button ng-click="Nerd.load()" type="button" class="btn btn-default">Cancel</button>
</form>
</div>
As you can see the cancel button calls a Nerd.load() function in the controller. The controller basically resets the view and resets all the binded data to the model.
Nerd.load = function () {
Nerd.editing = false;
Nerd.adding = false;
Nerd.nerd = [];
nerdResource.query(
function (data) {
Nerd.nerds = data;
}
);
};
You can see that I am setting Nerd.nerd equal to an empty array. This should empty out the form fields data. It works fine for Name and Phone. But when I go back to the page it still shows what was last typed. There is no page reload as I am showing and hiding divs based on controller variables. EG <div ng-show="Nerd.adding">. Can anyone help me out with this?
I am on angularjs version 1.3.14. Any help on this would be great.
Thanks.
You need to attach these variables to your $scope like so:
$scope.Nerd.load = function () {
$scope.Nerd.editing = false;
$scope.Nerd.adding = false;
$scope.Nerd.nerd = [];
nerdResource.query(
function (data) {
$scope.Nerd.nerds = data;
}
);
};
Also, I think you should set $scope.Nerd to an empty object like:
$scope.Nerd = {};
instead of setting it to an empty array. You need to use $scope when interacting with the view. This code doesn't look the angular the way it is currently written.
If you can try according some way.
Nerd.load = function () {
Nerd.editing = false;
Nerd.adding = false;
Nerd.nerd = [];
nerdResource.query(
function (data) {
Nerd.nerds = data;
Nerd.nerd = []; // Put here and array make Empty
}
);
};

Categories