"Error: Invalid ReCAPTCHA client id" when executing an invisible captcha - javascript

I'm trying to implement Google's Invisible reCAPTCHA in a HTML form in a Wordpress website.
In the head
First, I have the script that sets up the callbacks and binds the submit event of the form to the verification:
jQuery(document).ready(function() {
var valid = false;
window.recaptchaOkay = function(token) {
valid = true;
jQuery('#cadastro').submit();
};
document.getElementById('cadastro').addEventListener('submit', function validate(event) {
if (valid) {
return true;
}
var cap = document
.getElementById('cadastro')
.querySelector('.g-recaptcha');
grecaptcha.execute(cap);
event.preventDefault();
return false;
});
});
Then, I load the reCAPTCHA script, precisely as indicated in the documentation:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
In the body
And this is the form I'm using:
<form action="https://example.com/" method="post" id="cadastro">
<div
class="g-recaptcha"
data-sitekey="6Lc0jC4UAAAAANlXbqGWNlwyW_e1kEB89zLTfMer"
data-callback="recaptchaOkay"
data-size="invisible"
id="cadastro-captcha">
</div>
<button type="submit" id="cadastro-submit">Enviar</button>
</form>
What happens
I fill the form, submit it, and the following error is thrown (in the line with grecaptcha.execute):
Error: Invalid ReCAPTCHA client id: [object HTMLDivElement]
Also tried just passing the cadastro-captcha ID directly to that function as a string (e.g. grecaptcha.execute("cadastro-captcha")), yet the same error happens (bar the id being different, obviously). Equivalently, if I pass no argument, the same error happens, except it refers to undefined.

Try this one :--
The grecaptcha.reset() method accepts an optional widget_id parameter, and defaults to the first widget created if unspecified. A widget_id is returned from the grecaptcha.render() method for each widget created. So you need to store this id, and use it to reset that specific widget:
var widgetId = grecaptcha.render(container);
grecaptcha.reset(widgetId);
If More information then Read google recaptcha docs:--
https://developers.google.com/recaptcha/docs/display#js_api

Related

Passing multiple parameters from client HTML to server

I have a HTML form allowing users to fill out questionnaires, I would like to send the filled form as well as some variables (accessible within the HTML).
I've successfully sent filled form on it's own with...
HTML...
<button onclick="google.script.run.processForm(this.form)">Submit</button>
Javascript...
function processForm(formData) {...}
But when trying to send this.form along with extra variables / parameters, either via two parameters method...
<button onclick="google.script.run.processForm(this.form, var1)">Submit</button>
function processForm(formData, var1) {...}
or wrapped inside an array (below), both fails...
<button onclick="google.script.run.processForm([this.form, var1])">Submit</button>
function processForm(array) {...}
I've also tried declaring the array separately but same result...
HTML...
<? var arr = [this.form, var1] ?>
<button onclick="google.script.run.processForm(arr)">Submit</button>
JavaScript...
function processForm(arr) {...}
What am I doing wrong?
When the form object is sent to the Google Apps Script side using google.script.run, the form object is parsed on the internal server side and the value can be retrieved as an argument of the function at the Google Apps Script side. In this case, it seems that the 2nd argument cannot be used. I'm not sure whether this is the current specification or a bug.
If you want to include a value except for the form object, as a simple modification, how about the following sample script?
Sample script:
HTML & Javascript side:
<form>
<input type="text" name="input1">
<button onclick="sample(this.form);return false;">Submit</button>
</form>
<script>
function sample(e) {
const addValue = "sample"; // This is a value you want to add.
const input = document.createElement('input');
input.setAttribute('name', "addValue")
input.setAttribute('value', addValue);
e.appendChild(input);
google.script.run.processForm(e);
}
</script>
In this modification, a value you want to add is added to the form object. By this, the form object can be parsed by including the added value.
When this HTML is opened and put a sampe value of "test" into the input tag and the button is clicked, formData of function processForm(formData) {...} is {"addValue":"sample","input1":"test"}. So, you can retrieve your added value with formData.addValue.
Note:
As another direction, I think that the method that the form object is parsed and the value is included in the parsed value in the Javascript side can be also used. In this case, how about the following modification? In this case, in order to parse the form object, I used HtmlFormObjectParserForGoogleAppsScript_js.
HTML & Javascript side:
<script src="https://cdn.jsdelivr.net/gh/tanaikech/HtmlFormObjectParserForGoogleAppsScript_js/htmlFormObjectParserForGoogleAppsScript_js.min.js"></script>
<form>
<input type="text" name="input1">
<button onclick="sample(this);return false;">Submit</button>
</form>
<script>
async function sample(e) {
const addValue = "sample"; // This is a value you want to add.
const obj = await ParseFormObjectForGAS(e.parentNode); // Heare, this library is used.
obj.addValue = addValue;
google.script.run.processForm(obj);
}
</script>

How does prototype work for onSubmit:function()?

I was working on Co-drops Minimal Form Interface. I couldn't understand this code snippet in stepsForm.js. (Line 50)
stepsForm.prototype.options = {
onSubmit : function() { return true; }
};
I am new to JS, and wouldn't mind an explanation of the entire code in stepsForm if anyone has the time to do so. But, for the time being, an explanation for the above can do wonders for me. I know what a prototype is, but the onSubmit part is going over my head. I read on another question that this is to prevent refresh, but I feel that is wrong.
The library exposes options property that you may/can use to pass your own overriding values.This one in particular, exposes onSubmit.
For any html form an onSubmit is called when the submit action is invoked by another function or by click.
In the library the default onSubmit is returning true, meaning just execute the action. This can be overriden with you custom function like this...
<script>
var FORM_ELEMENT = document.getElementById( 'myForm' )
new stepsForm(FORM_ELEMENT, {
onSubmit :
function (FORM_ELEMENT) {
alert('You are about to submit the form ');
//manipulate your form or do any preprocess work...
return true;
});
</script>
Within the library the _submit (line 196 stepForm.js) is called which inturn calls the onSubmit. This time, instead of the default, it will execute the one we added above.
stepsForm.prototype._submit = function() {
this.options.onSubmit(this.el);
}
Hope that helps.

Validate dynamic input form elements using Validator Plugin Jquery

I am using this http://jqueryvalidation.org/ jquery validation plugin.
HTML dynamic form will be like this
<form name="baby_book" id="baby_book">
<input name="form_elements[16]" id="form_elements[16]">
<input name="form_elements[17]" id="form_elements[17]">
<input name="form_elements[18]" id="form_elements[18]">
<a class="myfont baby_book_save" href="javascript:void(0)" onclick="validatefilesizeform('save')" >Save</a>
</form>
My JS Code will be like this
<script type="text/javascript">
var validator="";
$(document).ready(function(){
var max_length_rules= <?php echo json_encode($valid_rules); ?>;
validator=$("#baby_book").validate();
$.each(max_length_rules,function(k,v){
$.each(v, function(key, value){
$('input[id="'+key+'"]').rules('add',"required");
});
});
});
function validatefilesizeform(type)
{
if(type == 'save')
{
document.baby_book.sec_submit.value="save";
if(validator.form())
{
document.baby_book.submit();
}
}
</script>
While applying dynamic rules like that it doesn't validate the form.
In console it displays this error
Uncaught TypeError: Cannot read property 'form' of undefined
Can anyone help me how to add dyanmic rules . Thanks.
That's because when the browser finds the validatefilesizeform('save') in the onclick attribute, it evaluates that expression, i.e runs the function. With this syntax you're asigning the result of that evaluation to the onclick event, which is not what you want.
The Cannot read property 'form' of undefined error happens because in that moment the $(document).ready() callback has not yet been executed, and, when the function tries to execute validator.form(), that variable is already undefined. It will be initialized later, inside the $(document).ready().
To get the expected behavior, and avoid the error, you must change the onclick handler to this one:
`onclick="function() { validatefilesizeform('save') }"`
In this case you're registering a function as the value for the onclick attribute. And this function will be evaluated when the control is clicked.
To make it even more clear:
// This is the value returned by the function evaluation:
validatefilesizeform('save')
// This is a function
function() { validatefilesizeform('save'); }
So the second is a function that can be evaluated. The first one evaluates the function. Handlers should always be functions, and not values.

Uncaught ReferenceError: findWeather is not defined

I am currently working on a simple web-app for my studies that shows the current weather per location and current weather on the location you type in.
I have in my HTML file:
<div id="data">
</div>
<input type="text" value="Which city are you in?">
<input type="button" value ="Submit" onclick="findWeather()">
and for the JavaScript file:
function findWeather() {
$.get("http://api.openweathermap.org/data/2.5/forecast?q=Eindhoven&appid=*My_APP_ID*",
function () {
document.getElementById("data").innerHTML = data.list.main.temp;
})
}
Of course I have filled in the right App ID, I'm just not sure whether to share it here or not.
The JavaScript script won't run and I have no clue why.
EDIT: I seem to getUncaught ReferenceError: findWeather is not defined
error, while I did declare findWeather..?
You haven't defined data.
Presumably it is supposed to be the first argument of the function you pass as the second argument to $.get.
After passing the URL, as a second argument of the .get() function you are passing a callback anonymous function. In this function you must declare the parameter in which the data should be stored. For example:
function findWeather(){
$.get("http://api.openweathermap.org/data/2.5/forecast?q=Eindhoven&appid=*My_APP_ID*",
function(data) {
document.getElementById("data").innerHTML = data.list.main.temp;
})
}

returning functions as string in javascript

I am in the process of writing a javascript object that contains a method that returns the html of a standard form. In this object I also have a method validate();
I'd like the form generated to use validate();
So the typical html of a form with validation would probably look like this:
<form id="a" onSubmit="return validate();">
The problem is that I need to be able to reference the object instance so
it would need to be more like onSubmit="my_object.validate();">
I've tried something like
return '<form id="a" onSubmit="return ' + this.validate + '();">';
but I get really strange behavior.
If I make the validate function arbitrarily return true the form gets submitted, false it doesn't. If I do any other calculations in the method I get this error:
> Error: syntax error Source Code:
> return id ==
Has anyone experienced anything like this?
Rather than outputting the event handler in the HTML attribute, you can output the HTML, get a reference to the form object, then attach an event handler programmatically, like this:
<html>
<head>
<script type="text/javascript">
var my_object = {
outputForm: function(container) {
container.innerHTML =
'<form id="a"><input type="submit" value="Validate" /></form>';
this.createdForm = document.getElementById('a');
this.createdForm.onsubmit = this.validate;
},
validate: function() {
// use this.createdForm to get at the controls.
alert("Who dares awake my slumber?");
}
};
function createTheForm() {
my_object.outputForm(document.getElementById('container'));
}
</script>
</head>
<body onload="createTheForm()">
<div id="container"></div>
</body>
</html>
sorry for posting this as an answer, after registering it wouldn't let me edit my original post as non registered user?
I thought about eval but I'm not sure how to even use it in this situation? I've tried it like so
' onSubmit="return eval(' + this.validate+'();)">';
and some other variations but I get the same error.
I would like to avoid having to manually add the event handling as I would like it to be pretty self contained. I was thinking about setting up a regular function which sits outside of the object and then doing something like
' onSubmit="return my_function(' + this + ');">';
then in my_function do this:
my_function(given){ return given.validate(); }
this seems like an awful hack and I'm not even sure if it will work.
Why are you not just applying it to the element after you add it to the page and using a closure to keep scope?
var myId = "bar" + index;
foo.innerHTML="<form id='" + myId + "'>...</form>";
var that = this;
document.getElementById(myId).onsubmit = function(){ that.validate(this); }
Adding event handlers to the markup is always a bad idea.
Use eval() to execute a string as javascript
[EDIT}
Sounds then like you need to prototype the form and then in submit call this.validate(). Get a reference to the form object when you create it using javascript and then define your method for validation and assign that to the validate property.

Categories