Im in the process of adding the reCaptcha from google to my form. The problem is that even though I have followed the instructions from google. I can still press the Submit button without doing the recaptcha. Any Ideas please heres the relevant code snippets.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>webpage title</title>
<link rel="stylesheet" type="text/css" href="view.css" media="all">
<script type="text/javascript" src="view.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
And the this snippet in the form part of the webpage
<div class="g-recaptcha" data-sitekey="xxxxxxmyapikeyxxxxxxx_xxxxxxmyapikeyxxxxxxx"></div>
<li class="buttons">
<input type="hidden" name="form_id" value="1136056" />
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
As far as I'm aware I have placed the code in the specified areas of my webpage. One before the closing tag on your HTML template and the snippet at the end of the where I want the reCAPTCHA widget to appear.
I have put the recaptcha before the submit button. There is a part about the server side integration that I do not understand.
[QUOTE]
When your users submit the form where you integrated reCAPTCHA, you'll
get as part of the payload a string with the name "g-recaptcha-response".
In order to check whether Google has verified that user,
send a POST request with these parameters:
URL: https://www.google.com/recaptcha/api/siteverify
secret (required) xxxxxmysecretkeyxxxxxxx
response (required) The value of 'g-recaptcha-response'.
remoteip The end user's ip address.
[/QUOTE]
Can anyone please shed some light on this please.
Thankyou
So we set up the form and make sure your library is included, I prevent the submit button from being clicked while the recaptcha has not been completed and show a tooltip to notify the user it is needed to continue. Then enable it when it has been complete using the callback methods.
login.php
<div class="formContainer">
<script src='https://www.google.com/recaptcha/api.js'></script>
<form action="loginHandler.php" method="post" name="login_form" id="loginForm" class="loginForm">
<h2>Login</h2>
<p><input type="text" required placeholder="Email" name="email"></p>
<p><input type="password" required placeholder="Password" name="password" id="password"></p>
<div class="g-recaptcha" data-callback="captcha_filled"
data-expired-callback="captcha_expired"
data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
</div>
<div>
<p class="show-tt" data-toggle="tooltip" title="Complete the reCAPTCHA to login." data-placement="bottom">
<input id="submitLogin" type="submit" value="Login">
</p>
</div>
</form>
</div>
<script>
//prevent submit and show tooltip until captch is complete.
var submit = false;
$("#submitLogin").prop('disabled', true);
function captcha_filled() {
submit = true;
$("#submitLogin").prop('disabled', false);
$(".show-tt").tooltip('destroy');
}
function captcha_expired() {
submit = false;
$("#submitLogin").prop('disabled', true);
showTooltip();
}
function showTooltip () {
$(".show-tt").tooltip('show');
}
</script>
Now we post to loginHandler.php, or wherever your form submits too and then there we will assign your secret key and then verify the request with google.
loginHandler.php
$secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
if (isset($_POST["g-recaptcha-response"])) {
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secret) .
'&response=' . urlencode($_POST['g-recaptcha-response']) . '&remoteip=' . urlencode($_SERVER['REMOTE_ADDR']);
//ip address is optional
$result = json_decode(file_get_contents($url), true);
if ($result != null && $result['success'] === true) {
//success, handle login/submit data or whatever
} else {
//response is bad, handle the error
header('Location: login.php?error=4');
}
} else {
//captcha response is not set, handle error
header('Location: login.php?error=5');
}
Related
I would like to know how to only allow #gmail.com and #yahoo.com for my email validation in html. I know about the <input type="email" validation but that would allow emails in any format and I only want those two to be accepted. How do I do it??
The only way is RegExp
If you are using a framework (angular/react/vue) they have there own(compatible third party) libraries to handle form validation.
If you are using plain JS you can add onchange event with your input and test the input with desired regex or before submitting the form you can test the input.
Regex you will need
/^[a-z][a-z0-9_.]*#(gmail|yahoo).com$/gm
More about Regex with Javascript:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Ok, it is not the best way of achieving this, for best way use it at backend, with PHP email validation filter.
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/css/master.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<form id="emailForm" action="" method="post">
<label for="email">E-mail</label><br>
<input id="email" type="email" name="email" placeholder="Please enter your
email" value="">
<button onclick="validate();" type="button" name="button">Submit</button>
</form>
</body>
</html>
Inline javascript, you can carry it later, keep it under html for testing purposes.
<script type="text/javascript">
function validate(){
var email = $('#email').val();
if (email.length == 0) {
window.alert("you didn't enter an email");
}
if (!email.includes('#')) {
window.alert("you mail is unvalid");
}
var emailHost = email.substr((-1)*(email.length - email.indexOf('#') - 1));
var allowedDomains = ["gmail.com","hotmail.com","yahoo.com"];
var inAllowed = false;
for(i=0;i<allowedDomains.length;i++){
if (allowedDomains[i] == emailHost) {
inAllowed = true;
}
}
if (!inAllowed) {
window.alert("your e-mail hosting not supported");
}else { //submit form here
window.alert("success");
$('#emailForm').submit();
}
}
</script>
And back end get email from $_POST if using php
<?php
var_dump($_POST);
?>
to demonstrate what im trying to do using a simple example:
<html>
<head>
<base target="_top">
</head>
<body>
<form id="uploaderForm" action="https://script.google.com/macros/.......exec Method="POST">
<input type="text" name="applicantName" id="applicantName">
<input type="text" name="applicantEmail" id="applicantEmail">
<input type="button" value="Submit">
</form>
<script>
.
.
.
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
</script>
so this is an example of the html and js page that is in my pc, not in the google app, i just called the google app in the form, and in the javascript part im calling a function called uploadFile, which is located in the google script, but obviously i get an error in the console , it says :
Uncaught ReferenceError: google is not defined
at uploadFiles (6166bff606ac6fee1994e592:67)
at HTMLInputElement.onclick
is it possible to call a GAS function inside JS that is not in the GAS html.
is what im trying to do even possible, the whoel reason im doing this is so that i can pass the username and email automatically from the database to the app, the app works if the html part is hosted in the google app script, but then i cant figure out how to pass the email and username to it because in this case i call the app using , so is it possible to pass the username and email through the iframe call, i dunno im very new to this i have so many questions, honestly the documentation wasn't helpful to me. please feel free to comment anything, everythign is helpful
Since you're just posting the form data, you can name the function you want to call as doPost()(instead of uploadFile) and it will receive the posted data. You have to republish the webapp as a new version after the modification.
I just ran it as a dialog. I returned the data back into the success handler and loaded by into the html to insure it was working.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<body>
<form>
<input type="text" name="applicantName" id="applicantName"/>
<input type="text" name="applicantEmail" id="applicantEmail"/>
<input type="button" value="Submit" onclick="uploadfile(this.parentNode);" />
</form>
<div id="msg"></div>
<script>
function uploadfile(form) {
google.script.run
.withSuccessHandler((m) => document.getElementById("msg").innerHTML = m)
.uploadMyFile(form);
}
</script>
</body>
</html>
gs:
function uploadMyFile(obj) {
return `Applicant Name: ${obj.applicantName}<br />Applicant Email: ${obj.applicantEmail}`;
}
function launchFormDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah2'),'Test Dialog');
}
Dialog:
I have this code:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="https://api.pagar.me/1/zipcodes/">
<input type="text" placeholder="cep" name="cep">
<input type="submit">
</form>
</body>
</html>
When I type a number, for example 05423110, I get on the adress bar is "https://api.pagar.me/1/zipcodes/?cep=05423110", but I would like to have "https://api.pagar.me/1/zipcodes/05423110".
What do I need to change on my code?
Thanks!
I would do it like this. The other answer will have the problem where it could potentially append something twice.
I also set it so the button disables for user friendliness (in case the server takes awhile to respond).
This solution does use jQuery, but chances are you will need to do other simple DOM manipulation and this will be very helpful.
Because you don't want the query string in there, but you must have it be GET, then its impossible not to have it append the query string to the URL (because that's what a GET request does).
Instead, I use javascript to simply redirect to the proper URL and ignore the form GET/POST entirely.
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="https://api.pagar.me/1/zipcodes/">
<input type="text" placeholder="cep" name="cep">
<input type="submit">
</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
(function() {
var form = $('form');
var baseUrl = form.attr('action');
$('form').submit(function(e) {
e.preventDefault();
form.find('[type="submit"]').prop('disabled', true);
window.location.href = baseUrl + form.find('[name="cep"]').val();
});
})();
</script>
Add method="post" to the form tag, then add an event listener to the form's submit event which append the input value to the action attribute value on the form:
const form = document.forms[0]
form.addEventListener('submit',()=>{form.action+=cep.value})
<form action="https://api.pagar.me/1/zipcodes/" method="post">
<input type="text" placeholder="cep" name="cep" id="cep">
<input type="submit">
</form>
Ofc StackOverflow snippets prevents POST.
I have created a small website using HTML service of Google apps script.
Here is GAS Code
function doGet() {
var t = HtmlService.createTemplateFromFile('form');
t.email=Session.getActiveUser().getEmail();
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
and this is HTML Code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<base target="_top">
</head>
<body onLoad="addEventListeners()">
<div class="container-fluid">
<form id="form1">
<label for="comp_indiv_name" id="company_individual_name" style="display: block" >2. COMPANY NAME</label>
<input type="text" class="form-control" name="cName" required>
<br>
<input type="submit" class="btn btn-primary" value="Create Contract Now">
</form>
</div>
<script>
function addEventListeners() {
var condition=true;
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
if(condition==true){condition=false;google.script.run.addData(this);}});
}
</script>
</body>
</html>
HTML page has one form with just one question, and when that form is submitted, the value get written in spreadsheet. Code for that is
function addData(form)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheet=ss.getSheetByName('test');
sheet.getRange(5,5).setValue(form.cName)
htmlPage();
}
All i want is once the value gets written on the sheet, this HTML page gets refreshed automatically. Right now it just stays as it is. Link to the HTML page is https://script.google.com/macros/s/AKfycbzavm6TPFOkIXj_V0uD8XIqMN-9w6jAgp_QgRkJXawFJF59rPU/exec
If you truly want to refresh the page, and not just clear the input field, then I would add a hidden link that has your web app URL, and then programatically "click" it when the server code has completed.
HTML
</form>
<a id="linkToThisWebApp" href="https://script.google.com/macros/s/webAppID/exec" style="display:none">Hidden</a>
<!-- <button onclick="reloadPg()">Test</button> -->
</div>
Script tag - Code with success handler
<script>
function addEventListeners() {
var condition=true;
document.getElementById('form1')
.addEventListener('submit',
function(e){
e.preventDefault();
if(condition==true){
condition=false;
google.script.run
.withSuccessHander(reloadPg)
.addData(this);
}
});
}
window.reloadPg = function() {//Runs when server code has completed
console.log('reloadPg ran');
document.getElementById('linkToThisWebApp').click();//Click the link
}
</script>
I am trying to do, form1 is hidden right now, if that username and password correct as in my code, than show form1 in same tab/window, so if username and password correct than next page says Hello! logged in, Is there any way that, i can do that?? I know i can create another html, if username and password correct than show that html, I can do that, I want to send html by email to if i send two html it won't work so, is there any way that i can do everything in one html, if username and password correct than show that hidden form.. Please help me!! Thanks!!
<!DOCTYPE html>
<!-- saved from url=(0042)http://jsfiddle.net/DrydenLong/RHwLW/show/ -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo by DrydenLong</title>
<script type="text/javascript" src="./- jsFiddle demo by DrydenLong_files/jquery-1.9.1.js"></script>
<script type="text/javascript" src="./- jsFiddle demo by DrydenLong_files/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="./- jsFiddle demo by DrydenLong_files/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="./- jsFiddle demo by DrydenLong_files/result-light.css">
<style type="text/css">
#hello, #sorry {
display: none;
}
</style>
<script type="text/javascript">//<![CDATA[
$(window).load(function(){
$(document).ready(function(){
$("#my_button").click(function(){
var userid = $("#user").val();
var pass = $("#pass").val();
if (userid == 'username' && pass == 'password') {
$("#login").fadeOut('slow', function () {
$("#hello").fadeIn();
});
} else {
$("#login").fadeOut('slow', function () {
$("#sorry").fadeIn();
});
}});});
});//]]>
</script>
</head>
<body>
<div id="login">
<form name="login">Username
<input type="text" name="userid" id="user">Password
<input type="password" name="pswrd" id="pass">
<input type="button" value="Login" id="my_button">
<input type="reset" value="Cancel">
</form>
</div>
<div id="hello">Hello! You are logged in.</div>
<div id="sorry">Sorry you have entered the wrong username or password</div>
</body></html>
Please help me!! Thanks!!
Ok, so this uses Jquery/JqueryUI to hide/show content based off of the values of your form fields. Depending on the values, the appropriate div is faded into view:
HTML
<div id="login">
<form name="login">Username
<input type="text" name="userid" id="user" />Password
<input type="password" name="pswrd" id="pass" />
<input type="button" value="Login" id="my_button"/>
<input type="reset" value="Cancel" />
</form>
</div>
<div id="hello">Hello! You are logged in.</div>
<div id="sorry">Sorry you have entered the wrong username or password</div>
CSS
#hello, #sorry {
display: none;
}
Jquery
$(document).ready(function () {
$("#my_button").click(function () {
var userid = $("#user").val();
var pass = $("#pass").val();
if (userid == 'username' && pass == 'password') {
$("#login").fadeOut('slow', function () {
$("#hello").fadeIn();
});
} else {
$("#login").fadeOut('slow', function () {
$("#sorry").fadeIn();
});
}
});
});
Now, there is a major problem with this code if you want your site to have secure content. Anybody can view the source code of your page and see the content that is being hidden, defeating the purpose of using a password to gain access. You will have to figure out a way to improve upon that if you want better security. If that's the case, you may want to look into a server-side scripting language such as PHP to address the security issue.
If security isn't a huge deal and the username/password is more for displaying the experience of what's in the div rather than the content, then this should do just fine.
Here is a fiddle with a working example: http://jsfiddle.net/DrydenLong/RHwLW/