Google App Script Closure error when calling script - javascript

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());

Related

Retrieving Data from Local Storage - key value pairs apparently don't match (error)

I am trying to make a functional login and registration pages (I know that in real life I need to store the login info in a database but for now I would like to see my pages "working"). I created two pages with forms one for registration and one for login. I also have two JS files one for locally storing input values (registerDetails.js) and one for retrieving those values during login (login.js).
Storing the information is not a problem, however, when I try to log in with the information I have just inputted and know it's correct it still throws an "Error" at me to say that password and username don't match even though I know they do match.
SOLUTION IN THE COMMENTS - MIX UP OF VARIABLES
I even tried to error handle if there is a problem with browser compatibility, still to no avail.
This is HTML for register.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Register or <a class="login-link" href="login.html">Login</a>
</legend>
<p>All fileds marked with * are required.</p>
</div>
<hr />
<div class="control-group">
<!-- Username -->
<label class="control-label" for="username"><span class="asterisk">*</span> Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Any letters or numbers without spaces"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email"><span class="asterisk">*</span> E-mail</label>
<div class="controls">
<input type="text" id="email" name="email" placeholder="Enter your email here" class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password"><span class="asterisk">*</span> Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password of atleast 4 characters"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password -->
<label class="control-label" for="password_confirm"><span class="asterisk">*</span> Confirm Password</label>
<div class="controls">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Please confirm password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button type="submit" id="register" class="btn btn-success" onClick="store()">
Register
</button>
</div>
</div>
</fieldset>
</form>
Here is my HTML for login.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Login or <a class="login-link" href="register.html">Register</a>
</legend>
</div>
<hr />
<div class="control-group">
<!-- Username or Email-->
<label class="control-label" for="username">Username or Email</label>
<div class="controls">
<input type="text" id="usernameEmail" name="usernameEmail" placeholder="Enter your email or username"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="passwordLogin" name="password" placeholder="Enter your password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" type="submit" onclick="check()">Login</button>
</div>
</div>
</fieldset>
</form>
My registration JS works fine, the browser prompts me to save credentials for later use...
Which is here:
// Getting details from the registration form to later store their values
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
// Locally storing input value from register-form
function store() {
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
My login page, however, throws the ERROR alert, even when I know for sure that the username and password match.
// check if stored data from register-form is equal to entered data in the login-form
function check() {
// stored data from the register-form
var storedName = localStorage.getItem('name');
// var storedEmail = localStorage.getItem('email');
var storedPassword = localStorage.getItem('password');
// entered data from the login-form
var userNameLogin = document.getElementById('usernameEmail');
var userPwLogin = document.getElementById('passwordLogin');
// check if stored data from register-form is equal to data from login form
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
alert('You are loged in.');
} else {
alert('ERROR.');
}
}
I have spent a few hours trying to rewrite the code to maybe see some typos or mistakes but I cannot find where I am going wrong! If anyone could help out as to show the reason why it does not match the username and password would be great.
It should alert me "You are logged in."
Thanks!
You have a typo
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
^^Here
}
Should be this instead
if (userNameLogin.value == storedName && userPwLogin.value == storedPassword ) {
}
By the way, your code will only log in with username (and not email) as it is. Don't forget to compare the email too.
Variables that are meant to store your elements at register page(userName, userEmail, etc.) might be null when store() is called.
I would suggest to get those inside the function:
function store() {
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
But the solution lies in this line:
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin)
In your case storedPassword doesn't have "value" and userPwLogin does, since userPwLogin is the element on your form
Your code isn't working right because you've mixed up your local storage variable with your input elements. This line:
if (userNameLogin.value === storedName && storedPassword.value === userPwLogin) {
it should be:
if (userNameLogin.value === storedName && userPwLogin.value === storedPassword) {

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.

Dropzone js validate on submit

I have a form where I am using dropzone.js for file upload. Now I am validating all the input fields. But i'm not able to validate the file before submission. If the file is uploaded, then the submission should work. Otherwise it should throw an error like - "please upload the file". How can i achieve this?
HTML code:
<form action="/action">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" required>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<textarea class="form-control" id="message" name="message" placeholder="Message"></textarea>
</div>
</div>
<div class="form-row">
<div id="resume" class="dropzone form-control"></div>
</div>
<input type="submit" class="btn btn-primary mt-10" id="item-submit" value="submit">
</form>
Javascript :
<script type="text/javascript">
$(document).ready(function () {
$("div#resume").dropzone({ url: "/change-this-later" });
var dropzone3;
Dropzone.autoDiscover = false;
dropzone3 = new Dropzone('#resume', {
maxFiles: 1,
});
$('#item-submit').click(function(e) {
e.preventDefault();
e.stopPropagation();
if ($('form#resume').valid()) {};
});
});
</script>
You can add a callback event which is called if the upload is successful
//indicates file upload is complete and is successful
var uploaded = false;
$("div#resume").dropzone({
url: "/change-this-later",
success: function (file, response) {
uploaded = true;
}
});
//Check the value of 'uploaded' when validating rest of fields
So I come around this. Since I submit all my images and fields in the same button, I just acceded to the files array in side the dropzone and validate that it's lenght wasn't 0. $animalImage is my dropzone.
var validateImages = function (animal) {
if ($animalImage.files.length == 0) {
swal({
title: 'Advertencia',
type: 'info',
html: "Debe de guardar al menos una imágen",
showCloseButton: true,
focusConfirm: false
});
return false;
}
return animal;
};
Hope it helps, side note a submit trough ajax so I just used dropzone for the user experience.

How do I export Google Script form data to Google Drive?

I have built a very simple form in google scripts. The file upload feature is functional: it uploads a file to my google drive. I cannot figure out how to grab the form information (Name, Organization, Content Type), save it into a spreadsheet, and upload that to my google drive.
How do I upload the form data (text fields) to my drive?
!!UPDATE 7/19!!
Code updated with Spreadsheet App code. and improved HTML. CSS not included as I don't think it's relevant to this issue.
!!UPDATE 7/20!!
Code is working. Updated to reflect full functionality. Thanks to Sandy for the assistance.
form.html
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<div id="main">
<div class="form">
<form id='myForm'>
<div class="header">
<h1>Information Submission Form</h1>
<h2>Center For Alternative Fuels</h2>
</div>
<div class="row">
<div class="col-md-6">
<input id='name' type="text" name="name" placeholder="Full name" class="full item" spellcheck="false">
</div>
<div class="col-md-6">
<input id='email' type="text" name="email" placeholder="Email" class="full item" spellcheck="false">
</div>
</div>
<div class="row indent item">
<input id='organization' type="text" name="organization" placeholder="Organization" class="full" spellcheck="false">
</div>
<div class="row indent item">
<textarea id='type' name="type" class="full" placeholder="What are you submitting? (Presentation, Educational Content,...)" rows='2'></textarea>
</div>
<div id='success'>
</div>
<div class="row indent item">
<textarea id='info' name="info" class="full" placeholder="Describe the content you are submitting" rows='8'></textarea>
</div>
<input type="file" name="myFile">
<input type="submit" value="Submit"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;" style="margin-top: 20px">
</form>
</div>
</div>
<div id="output"></div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
server.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
var url;
function uploadToSheet(form){
var fullName, emailAdd, organization, fileType, fileInfo;
var ss = SpreadsheetApp.openById("INSERT SHEET ID HERE");
var dataArray = [];
fullName = form.name;
emailAdd = form.email;
organization = form.organization;
fileType = form.type;
fileInfo = form.info;
dataArray.push(fullName);
dataArray.push(emailAdd);
dataArray.push(organization);
dataArray.push(fileType);
dataArray.push(fileInfo);
ss.appendRow('dataArray');
}
function uploadFiles(form) {
try {
var dropbox = "Form Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
}
else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
url=file.getUrl();
return "File uploaded successfully " + file.getUrl();
}
catch (error) {
return error.toString();
}
}
The code might look something like this:
var dataArray,org,ss,userName;
ss = SpreadsheetApp.openById("spreadsheet_File_ID");
dataArray = [];
userName = form.myName;
org = form.myOrganization;
dataArray.push(userName);
dataArray.push(org);
ss.appendRow(dataArray);

Implemented reCaptcha... Still getting spam

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

Categories