I use the userClicked() in code.gs of my google apps script to save some data if the user password in login.html is correct.
How can I redirect the user to page.html after saving data in line #18?
I want to redirect only if the password is correct. So I can't use simple on the login page.
Code.gs file
login.html
code.gs
function doGet(e) {
if (!e.parameters.v){
return HtmlService.createTemplateFromFile("login").evaluate();
}
else {
return HtmlService.createTemplateFromFile(e.parameters['v']).evaluate();
}
}
function userClicked(userInfo){
if (userInfo.userPassword && userInfo.userPassword == userInfo.dbPassword){
/* save page data in a google spreadsheet */
var ss = SpreadsheetApp.openById("1OU6y0Iid5r2xGcfxZpUqGzZjZo8Gz7rALkYcajCslN8"); // calls "DB_" spreadsheet
var ws = ss.getSheetByName("Sheet1");
var lastRow = ws.getRange("A1").getDataRegion().getLastRow(); // get last row of column A
var lastRow1 = lastRow + 1;
ws.getRange("A"+ lastRow1 +":D"+ lastRow1).setValues([[new Date(), userInfo.userName, userInfo.userPassword, userInfo.dbPassword ]]);
}
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function lookup(pass){
var ss = SpreadsheetApp.openById("1gBo8UrCpqtQ5Rf67HCriEDRhJeQuhvPZ1vebeTHndt0"); // calls "Therapists" spreadsheet
var ws = ss.getSheetByName("Therapists");
var data = ws.getRange(1, 4, ws.getLastRow(), 2).getValues();
var therapistsList = data.map(function(r){ return r[0];});
var passwordsList = data.map(function(r){ return r[1];});
var position = therapistsList.indexOf(pass);
if (position > -1){
return passwordsList[position];
}
else {
return 'Not Found!';
}
}
Login.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include("css"); ?>
</head>
<body>
<div class="container">
<p>Login</p>
<div class="row">
<div class="input-field col s3">
<input id="username" type="text" class="validate">
<label for="username">Username</label>
</div>
<div class="input-field col s3">
<input disabled id="dbPass" type="text" class="validate">
<label for="dbPass">Database Pass</label>
</div>
</div><!-- row -->
<div class="row">
<div class="input-field col s3">
<input id="userPass" type="text" class="validate">
<label for="userPass">Password</label>
</div>
</div><!-- row -->
<div class="row">
<button id="btn" class="waves-effect waves-light btn-small blue accent-4"><i class="material-icons left">play_arrow</i>submit</button>
</div>
</div> <!-- Container -->
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include("js_"); ?>
</body>
</html>
add tag and surround inside all your input field and other elements that take values from user.use return attribute with your function name. Return attribute does is; if your function returns true you can direct return false, you can't redirect
Ex:
<form onsubmit="return productsvalidationform();" method="POST" action="AddProductServlet">
<div class="form-group">
<label>Product Name</label><br> <input type="text" required class="form-control" name="ProductName" placeholder="productname" id="productname">
</div>
</form>
productsvalidationform(); is the function,This function return true or false.If true we can be redirected to AddProductServlet.In the form tag, include action attribute that describes where you want to go.
Related
I have a small sidebar form that submits user data. It is all functional for anyone in the USA but if someone from overseas tries to submit the form, it fails. I even logged into the same user account as the one overseas and the form submits for me. I have never encountered an issue like this with GAS. The account the user is logged into owns the spreadsheet that the script is housed in and he has tried both local and US IP addresses to submit the data (not sure if this even matters.) What do I need to change/include in my scripts to allow all users to be able to submit the form? Would creating a Webapp and trigger be a fix?
Code.gs
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
//PROCESS FORM DATA
function processForm(formObject){
var notes = [formObject.client,
formObject.website,
formObject.email,
formObject.plan];
var mTabs = [formObject.client,
formObject.plan,
formObject.timeAllowed,
'',
'',
'00:00:00.000'];
pushToSheets(notes,mTabs);
}
//INCLUDE HTML PARTS, EG. JAVASCRIPT, CSS, OTHER HTML FILES
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
//THIS FUNCTION IS USED TO PUSH DATA TO EACH RESPECTIVE SHEET FROM THE SIDEBAR FORM SUBMISSION
function pushToSheets(notes,mTabs) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var noteTab = ss.getSheetByName('NOTES');
var sheetArr = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEPT','OCT','NOV','DEC'];
// var sheetArr = ['JAN','FEB'];
var nLast = noteTab.getLastRow();
noteTab.insertRowBefore(nLast+1);
noteTab.getRange(nLast+1, 1,1,4).setValues([notes]);
noteTab.getRange(2,1,nLast+1,17).sort([{column: 4, ascending: true}, {column: 1, ascending: true}])
for(var x = 0; x < sheetArr.length; x++) {
var sheet = ss.getSheetByName(sheetArr[x]);
var sLength = sheet.getLastRow();
sheet.insertRowBefore(sLength-1);
sheet.getRange(sLength-1, 1,1,6).setValues([mTabs]);
sheet.getRange(2, 1,sLength,11).sort([{column: 2, ascending: true}, {column: 1, ascending: true}])
}
}
Index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<?!= include('JavaScript'); ?> <!-- See JavaScript.html file -->
<title>Contact Details</title>
</head>
<body class="bg-secondary text-light">
<div class="container">
<?!= include('Form'); ?> <!-- See Form.html file -->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$('#timeAllowed').keypress(function() {
var regex = new RegExp("^[0-9]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
if(this.value.length == 2){
this.value = this.value+':';
}
if(this.value.length == 5){
this.value = this.value+':00';
}
if(this.value.length > 7) {
return false;
}
});
</script>
</body>
</html>
Form.html
<form id="myForm" onsubmit="handleFormSubmit(this)" autocomplete="off">
<div class="form-group">
<label for="client">Client</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="clint" name="client" placeholder="Client Name">
</div>
<div class="form-group">
<label for="gender">Plan</label>
<select class="form-control form-control-sm" id="plan" name="plan" required>
<option value="" selected disabled>Choose...</option>
<option value="00 hosting">00 hosting</option>
<option value="01 slim">01 slim</option>
<option value="02 basic">02 basic</option>
<option value="10 special">10 special</option>
<option value="99 coming up">99 coming up</option>
</select>
</div>
<div class="form-group">
<label for="last_name">Time Allowed</label>
<input class="form-control form-control-sm" type="text" class="form-control" pattern="[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" title ="00:00:00" id="timeAllowed" name="timeAllowed" placeholder="00:00:00">
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control form-control-sm" type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="website">Website</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="website" name="website">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
JavaScript.html
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
Looks like I just needed to add this as a Webapp and that fixed the issue. Thank you for the suggestions!
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('test').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
function doGet() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
form.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return form;
}
test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<center>
<embed type="text/html" src="redacted" width="290" height="800">
</center>
</body>
</html>
I am building a html form which based on that, when user submits his/her name it should return an integer representing sum of all bought items by user, the return value from API is a list of json formate, which looks like this:
[{"Phone":800}, {"laptop":1500}, {"car":12000},{"watch":300}]
This is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="MyMain.css">
<script language="JavaScript">
function myFunction() {
document.getElementById('myshow').innerHTML =
document.getElementById("Name").value;
return false;
}
</script>
</head>
<body>
<div class="container">
<div>
<fieldset>
<form method="POST" action="" onSubmit="return myFunction();">
<div class="row">
<div form-group">
<label for="fname">Your Name: </label>
<input type="text" class="form-control" name="name" id="Name" placeholder="Jon" value="">
</div>
</div>
<div>
<input type="submit" class="button" value="Submit"><br/>
</div>
</div>
</form>
</fieldset>
</div>
</div>
<div class="container">
<fieldset>
<div>
<label>Prices: </label>
<p><span id='myshow'></span></p>
</div>
</fieldset>
</div>
</body>
</html>
I have no idea how to get that response and how to sum values of items!
Short answer of your question is :
var a = '[{"Phone":800}, {"laptop":1500}, {"car":12000},{"watch":300}]';
// parse your json to object if your json is string and not generated by js
a = JSON.parse(a);
var sum = 0;
Object.values(a).forEach(function(ww){
sum += Object.values(ww)[0]; // get sum of every object item value.
});
console.log(sum);
Use reduce() method in JavaScript.
let data = [{"Phone":1}, {"laptop":1}, {"car":1},{"watch":1}]
let total = data.reduce((acc, value) => {
return acc + value[Object.keys(value)[0]]
}, 0)
console.log(total);
Today I am going to use JavaScript to do a validation of the registration page, but after an afternoon of verification, the function can be called. When the test pop-up window is added at the beginning of the function, the pop-up window pops up correctly, but the verification function in the function is always unresponsive. Ask for the forum's amnesty, where is the problem, thank you! ! !
I added a test popup statement to the script and it succeeded. But other functions don't respond.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册界面</title>
<link rel="stylesheet" type="text/css" href="css/register.css">
<script type="text/javascript">
window.alert("test");
function checkRegisterINfo(form) {
/*判断姓名格式是否正确*/
var RegisterNameCheck = document.getElementById("nameId").value;
if (RegisterNameCheck = "") {
window.alert("姓名不能为空!");
return false;
} else {
var rightName = /[\u4E00-\u9FA5]{2,16}/;
if (rigntName.test(RegisterNameCheck) == true) {} else {
window.alert("您输入的姓名不正确!");
return false;
}
}
/*判断密码是否规范*/
var RegisterPwdCheck = document.getElementById("pwdId").value;
var rightPwd = /^(\w){6,20}$/;
if (rightPwd.test(RegisterPwdCheck) == false) {
window.alert("密码只能输入6-20个字母、数字、下划线");
return false;
}
/*判断密保问题格式是否正确*/
var RegisterQuestionCheck = document.getElementById("questionId").value;
var rightQuestion = /[\u4E00-\u9FA5]{1,16}/;
if (!rightQuestion.test(RegisterQuestionCheck)) {
window.alert("密保问题支持1-16位汉字!");
return false;
}
/*判断密保答案格式是否正确*/
var RegisterAnswerCheck = document.getElementById("answerId").value;
var rightAnswer = /[\u4E00-\u9FA5]{1,50}/;
if (!rightAnswer.test(RegisterAnswerCheck)) {
window.alert("密保答案支持1-50位汉字!");
return false;
}
}
</script>
</head>
<body>
<div class="main">
<div class="title">
<span>用户注册</span>
</div>
<form name="registerForm" method="post" action="" onsubmit="return checkRegisterINfo(registerForm)">
<!--输入框-->
<div class="input-content">
<div>
<input type="text" autocomplete="off" id="nameId" placeholder="用户名" name="Registerusername" required/>
</div>
<div style="margin-top: 16px">
<input type="password" autocomplete="off" id="pwdId" placeholder="登录密码" name="Registerpassword" required maxlength="32" />
</div>
<div style="margin-top: 16px">
<input type="text" autocomplete="off" id="questionId" placeholder="密保问题" name="Registerquestion" required maxlength="32" />
</div>
<div style="margin-top: 16px">
<input type="text" autocomplete="off" id="answerId" placeholder="密保答案" name="Registeranswer" required maxlength="32" />
</div>
</div>
<!--登入按钮-->
<div style="margin-top: 105px">
<button type="submit" class="enter-btn">登录</button>
</div>
<div class="foor">
<div class="left"><span>忘记密码</span></div>
<div class="right"><span>用户登录</span></div>
</div>
</form>
</div>
</body>
</html>
I am using JavaScript in JSP page and trying to display errors in all fields if no value is provided in the input field.. but for some reason error message is displayed only for the the first field which is field label.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>Test</title>
</head>
<body>
<div class="container">
<br>
<h1 class="text-success text-center">Test Test</h1>
<div class="col-lg-8 m-auto d block">
<form action="#" onsubmit="return validation()" class="bg-light">
<div class="form-group">
<label>FieldLabel:</label> <input type="text" name="fieldLabel"
class="form-control" id="fieldLabel"></input> <span
id="fieldLabelError" class="text-danger"></span>
</div>
<div class="form-group">
<label>Version:</label> <input type="text" name="version"
class="form-control" id="version"></input> <span id="versionError"
class="text-danger"></span>
</div>
<input id="submit" name="submit" type="submit" value="Submit"
onclick="validation()">
</form>
</div>
</div>
<script type="text/javascript">
function validation() {
var fieldLabel = document.getElementById("fieldLabel").value;
var version = document.getElementById("version").value;
if (fieldLabel == "") {
document.getElementById("fieldLabelError").innerHTML = "**Please enter Field label";
return false;
}
if (version == "") {
document.getElementById("versionError").innerHTML = "**Please enter version";
return false;
}
return true;
}
</script>
</body>
</html>
Because in the validation() function when fieldLabel is empty then you will return false,so the version have no chance to execute,change your code as below:
function validation() {
var fieldLabel = document.getElementById("fieldLabel").value;
var version = document.getElementById("version").value;
var isValid = true;
if (fieldLabel == "") {
document.getElementById("fieldLabelError").innerHTML = "**Please enter Field label";
isValid = false;//use a variable to set the result
}
if (version == "") {
document.getElementById("versionError").innerHTML = "**Please enter version";
isValid = false;
}
return isValid;
}
So I am working on this project and I use a barcode scanner that has Windows CE 5.0 as its operating system. whenever I scan the barcode, the page automatically refreshes which should not. After it scans the barcode the user should be able to enter a number for quantity and after that the user will click the preview button which will take the user to another page. I've searched the net for solutions for this problem but still does not work. Help Please. Thank you.
<?php
include("webconfig.php");
ob_start();
session_start();
if(!isset($_SESSION["USER_CODE"]) || $_SESSION["ACTIVE"] == '0')
header("location:login.php");
$barcode = $_REQUEST["barcode"];
$item_desc = $_REQUEST["item_desc"];
$price = $_REQUEST["price"];
$quantity = $_REQUEST["txtQty"];
$pricef = number_format($price, 2);
$sql = ibase_query($conn, "SELECT * FROM ITEM_MASTER WHERE ITEM_CODE = '$barcode'") or die(ibase_errmsg());
$row = ibase_fetch_assoc($sql);
$imgname = $row['IMGNAME'];
?>
<!DOCTYPE html>
<html>
<head>
<link href="docs/css/metro.css" rel="stylesheet">
<link href="docs/css/metro-icons.css" rel="stylesheet">
<link href="docs/css/docs.css" rel="stylesheet">
<script src="docs/js/jquery-2.1.3.min.js"></script>
<script src="docs/js/metro.js"></script>
<script src="docs/js/docs.js"></script>
<script src="docs/js/prettify/run_prettify.js"></script>
<script src="docs/js/ga.js"></script>
<script src="js/jquery.js"></script>
<script src="js/jquery.ajaxcomplete.js"></script>
<script type="text/javascript" src="keyboard.js" charset="UTF-8"></script>
<link rel="stylesheet" type="text/css" href="keyboard.css">
<link rel="shortcut icon" href="_img/assigns-favicon.PNG">
<title>Albert Smith Signs - Warehouse Inventory System</title>
</head>
<body>
<div class="page-content">
<div class="align-center">
<div class="container">
<!-- Default -->
<div class="panel">
<div class="content">
<div class="grid">
<div class="row cells12">
<!-- Default -->
<div class="panel">
<div class="heading">
<span class="title">ENTER QUANTITY</span>
</div>
<div class="content">
<div class="grid">
<div class="row cells12">
<div class="cell colspan12">
<form onsubmit="return false;" method="post">
<label>Enter Quantity</label>
<br />
<div class="input-control text full-size" placeholder="Type search keyword here" data-role="input">
<!-- <input name="txtQty" class="keyboardInput" style="width: 225px;" type="text" value="1" autocomplete="off" /> -->
Scan Barcode
<input name="txtBarcode" id="ip" type="text" autofocus />
<br />
<br />
Enter Quantity
<input name="txtQty" id="next" type="text" />
</div>
<div class="cell colspan12">
<hr>
<br />
<br />
<br />
<br />
<br />
<input type="submit" onsubmit="return true;" name="btnPreview" style="width:80px; height:50px;" class="button primary rounded large-button" value="Preview" />
</div>
</div>
<?php
if(isset($_POST['btnPreview']) && $_POST['txtQty'] > 0)
{
$quantity = $_POST['txtQty'];
$barcode = $_POST['txtBarcode'];
$sql = "SELECT * FROM ITEM_MASTER WHERE ITEM_CODE = '$barcode'";
$query = ibase_query($conn, $sql) or die(ibase_errmsg());
if ($row = ibase_fetch_assoc($query))
{
$item_desc = $row['ITEM_DESC'];
$price = $row['COST'];
header("location:preview.php?barcode=$barcode&quantity=$quantity&item_desc=$item_desc&price=$price");
}
else{
echo "Barcode not found";
}
}
?>
</form>
<div class="cell colspan1">
</div>
</div>
</div>
</div>
</div><!-- panel -->
</div><!-- row cells12 -->
</div><!-- grid -->
</div><!-- content -->
</div><!-- panel -->
</div>
</div>
</div>
<script>
//$("#ip").focus();
/*var d = false;
$("#ip").on('change', function(){
//$("#ip").keyup(function(){
if(d == false){
$(".block").animate({"top": "-=50px"});
d = true;
}
var v = $(this).val();
$(".res").html("Search results for " + v );
$("#next").focus();
});*/
$("#ip").focus();
function init() {
key_count_global = 0; // Global variable
document.getElementById("ip").onkeypress = function() {
key_count_global++;
setTimeout("lookup("+key_count_global+")", 1000);//Function will be called 1 second after user types anything. Feel free to change this value.
}
}
window.onload = init; //or $(document).ready(init); - for jQuery
function lookup(key_count) {
if(key_count == key_count_global) { // The control will reach this point 1 second after user stops typing.
// Do the ajax lookup here.
$("#next").focus();
}
}
</script>
</body>
</html>
It is supposed to do that. But you can stop it this way:
<form method="post" name="form" id="form" onsubmit="return false;">
Add this to your FORM like you see above.
onsubmit="return false;"
That will stop it from refreshing the page.