Loading the arrays from server when DOMContentLoaded - html

I try to get the contents of 3 arrays from spreadsheet in 3 vars when the page is loaded in DOMContentLoaded. But I get nothing (look the picture)
I deployed the test project here: https://script.google.com/a/fmlogistic.com/macros/s/AKfycbxROleHY3u69jTpdVZjLOfDTzY9c5q1S4kwm0ctTFzU/dev
and test-spreadsheet with script of this is here
https://docs.google.com/spreadsheets/d/1qxr91eiLUykfLS0zKq3D4Dn206vnEkVqxDo6ZQF1rU4/edit#gid=0
I tried to write something like here, but this way with variantes Apps script return values from server function to html form
const inputs = document.querySelector('.dws-input');
const formControl = document.querySelectorAll('.form-control');
let findData;
let curInpID;
let firstValid, secValid, thirdValid, allValid;
formControl[0].focus();
function callBack(e) {
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
}
document.addEventListener("DOMContentLoaded", function(){
google.script.run.withSuccessHandler(callBack).sendData();
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
console.log(Logs);
console.log(Tabs);
console.log(Ords);
});
<!doctype html>
<html lang="en">
<head>
<title>CLR: PACKING</title>
<meta charset = "UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name= "username" placeholder= "Login:" autofocus >
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name= "text" placeholder= "Table:" >
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name= "text" placeholder= "Order:" >
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>
<?!= include("index-js"); ?>
</body>
</html>
In actions.gs at server I wrote this:
const url = SpreadsheetApp.getActiveSpreadsheet().getUrl();
var htmlServ = HtmlService.createTemplateFromFile("index");
let ss = SpreadsheetApp.openByUrl(url);
let sheetTo = ss.getSheetByName("#sistem");
let sheetIn = ss.getSheetByName("#packing");
function doGet(e){
return htmlServ.evaluate();
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function sendData(){
var lrLogins = sheetTo.getRange("A:A").getValues().filter(String).length;
var arrLogins = sheetTo.getRange(1, 1, lrLogins, 1).getValues().flat();
var lrTMPLORDS = sheetTo.getRange("K:K").getValues().filter(String).length;
var curTMPLORDS = sheetTo.getRange(1, 11, lrTMPLORDS, 1).getValues();
var lrTABLES = sheetTo.getRange("R:R").getValues().filter(String).length;
var curTABLES = sheetTo.getRange(1, 18, lrTABLES, 1).getValues().flat();
var objDataInfo = {};
objDataInfo.ListLogins = arrLogins;
objDataInfo.ListTables = curTABLES;
objDataInfo.ListOrders = curTMPLORDS;
return objDataInfo;
}
Are there any ways to get the contents of these arrays when the page is loaded

Try this:
function callBack(e) {
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
console.log(Logs);
console.log(Tabs);
console.log(Ords);
}
document.addEventListener("DOMContentLoaded", function(){
google.script.run.withSuccessHandler(callBack).sendData();
//the following code is not in the callback function and it get's executed probably before the callback is returned.
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
console.log(Logs);
console.log(Tabs);
console.log(Ords);
});
It could have been written like this:
document.addEventListener("DOMContentLoaded", function () {
google.script.run.withSuccessHandler(function(e){
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
console.log(Logs);
console.log(Tabs);
console.log(Ords);
}).sendData();
});

Related

upload files into google drive folder from side bar UI

I am trying to make web app as a sidebar in spreadsheet using HTML5, Bootstrap 5 & JavaScript to make entry of data easier . I managed to go through the entire process But the problem that I can't make the button upload files into google drive folder and return with the url back.
the link of sheet working with.
I think the problem in this variable from html script but I don't know what is it
var url = document.getElementById("transaction-file").addEventListener('click',
function(a){
google.script.run.uploadFiles(this.parentNode)
});
https://docs.google.com/spreadsheets/d/1D-tEPsUJqGbCHrF8CYQlPu_ZhmVIGDYEojHfO0_7rW4/edit?usp=sharing
google script code
function loadForm() {
const htmlForSidebar = HtmlService.createTemplateFromFile("uform");
const htmlOutput = htmlForSidebar.evaluate();
htmlOutput.setTitle("Winter 2021");
const ui = SpreadsheetApp.getUi();
ui.showSidebar(htmlOutput);
}
function createMenu(){
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu("My Forms");
menu.addItem("Show UserForm", "loadForm");
menu.addToUi();
}
function onOpen(){
createMenu();
}
function uploadFiles(files){
var file = files.myFile;
var folder = DriveApp.getFolderById('1gaNAb1s8j7wmotvRUJbg4yfJOFNdZYo5');
var createFile = folder.createFile(file);
return createFile.geturl();
}
function addNewRow(rowData) {
const currentDate = new Date();
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Sheet1");
ws.appendRow([currentDate, rowData.trxDate, rowData.account, rowData.trxID, rowData.amount, rowData.url, rowData.comment]);
return true;
}
function getDropDownArray(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Ref");
return ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<div class="container pt-3">
<h4 class="border-bottom pb-2 mb-4">Donations' Registration <span class="badge bg-secondary">Form</span></h4>
<div id="userform">
<div class="mb-3">
<label for="transaction-date" class="form-label">Transaction Date</label>
<input type="date" class="form-control" id="transaction-date" required>
<div class="invalid-feedback">Please enter valid date.</div>
</div>
<div class="mb-3">
<label for="transaction-account" class="form-label">Account</label>
<select class="form-select" id="transaction-account" required aria-label="select account" required>
</select>
<div class="invalid-feedback">Please enter valid account.</div>
</div>
<div class="mb-3">
<label for="transaction-id" class="form-label">Transaction ID</label>
<input type="text" class="form-control" id="transaction-id" required>
<div class="invalid-feedback">Please enter valid ID.</div>
</div>
<div class="mb-3">
<label for="transaction-amount" class="form-label">Amount</label>
<input type="number" class="form-control" id="transaction-amount" required>
<div class="invalid-feedback">Please enter valid amount without any service fees.</div>
</div>
<div class="mb-3">
<label for="transaction-file" class="form-label">url</label>
<input type="file" class="form-control" id="transaction-file" name="myFile" aria-label="file example" required>
<div class="invalid-feedback">Please upload right file.</div>
</div>
<div class="mb-3">
<label for="transaction-memo" class="form-label">Memo</label>
<textarea class="form-control" id="transaction-memo" rows="1"></textarea>
</div>
<div class="mb-3">
<button class="btn btn-primary" id="mainButton">Add to Database</button>
</div>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
-->
<script>
function afterButtonClicked(){
if(validate()){
var trxDate = document.getElementById("transaction-date");
var account = document.getElementById("transaction-account");
var trxID = document.getElementById("transaction-id");
var amount = document.getElementById("transaction-amount");
var url = document.getElementById("transaction-file");
var comment = document.getElementById("transaction-memo");
var rowData = {trxDate: trxDate.value, account: account.value, trxID: trxID.value, amount: amount.value, url: url.value, comment: comment.value};
google.script.run.withSuccessHandler(afterSubmit).addNewRow(rowData);
} else {
//handle this later
}
}
function afterSubmit(e){
clearFields(["transaction-date", "transaction-account", "transaction-id", "transaction-amount", "transaction-file", "transaction-memo"]);
}
function clearFields(fields){
fields.forEach(function(field){
var el = document.getElementById(field);
el.value = "";
});
}
function validate(){
var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
//is-invalid
Array.prototype.forEach.call(fieldsToValidate,function(el){
if(el.checkValidity()){
el.classList.remove("is-invalid");
} else {
el.classList.add("is-invalid");
}
});
return Array.prototype.every.call(fieldsToValidate,function(el){
return el.checkValidity();
});
}
function afterSidebarLoads(){
google.script.run.withSuccessHandler(afterDropDownArrayReturned).getDropDownArray();
}
function afterDropDownArrayReturned(arrayOfArrays){
var account = document.getElementById("transaction-account");
arrayOfArrays.forEach(function(r){
var option = document.createElement("option");
option.textContent = r[0];
account.appendChild(option);
});
}
document.getElementById("mainButton").addEventListener("click",afterButtonClicked);
google.script.run.uploadFiles(this.parentNode);
document.addEventListener("DOMContentLoaded",afterSidebarLoads);
</script>
</body>
</html>

Apps Script: Collect Form Input and Display Today's Total

First time poster here: I've created a web app in Apps Script where the user enters:
Date
Food
Quantity
...then the associated 'health points' are calculated and added to a spreadsheet in Google Sheets.
What I want to do is calculate and display the day's total and then recalculate and display whenever the form is submitted. I'm still a newer JS user, so I'm cheating a bit by calculating in Google Sheets. Here's what that formula looks like:
=sum(ArrayFormula(if(today()-1=Data!A:A,Data!B:B,0)))
..then I'm passing that as a template value. That works when loading the page, but I would like it to update whenever the form is submitted.
Do you have ideas on how to calculate today's total using a script instead of Sheets and recalculating/displaying when the form is submitted?
Update: I've attached the code. And here's the sheet: https://docs.google.com/spreadsheets/d/1pXtOAnVJOkz1DGKir79pxoMUG85LPSfoN4SSVUk0a1k/edit?usp=sharing
function doGet(request) {
var t = HtmlService.createTemplateFromFile('index');
var url = "https://docs.google.com/spreadsheets/d/1pXtOAnVJOkz1DGKir79pxoMUG85LPSfoN4SSVUk0a1k/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Points");
var total = ws.getRange(1,1,1,1).getValue();
var remaining = 25-total;
Logger.log(total);
Logger.log(remaining);
t.total = total;
t.remaining = remaining;
return t.evaluate();
}
function getLast() {
var url = "https://docs.google.com/spreadsheets/d/1pXtOAnVJOkz1DGKir79pxoMUG85LPSfoN4SSVUk0a1k/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
var last = ws.getLastRow();
Logger.log(last);
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* #Process Form */
function processForm(formObject) {
// (Calories * .0305) + (Sat Fat * .275) + (Sugar * .12) - (Protein * .098)
var smartpointsServing = Math.round((formObject.calories * .0305) + (formObject.satfat * .275) + (formObject.sugar * .12) - (formObject.protein * .098));
// var formattedDate = Utilities.formatDate(new Date(formObject.today), "GMT-6", "MM/dd/yyyy");
var url = "https://docs.google.com/spreadsheets/d/1pXtOAnVJOkz1DGKir79pxoMUG85LPSfoN4SSVUk0a1k/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Foods");
var ws2 = ss.getSheetByName("Data");
var newFoodHp = smartpointsServing*formObject.quantity;
if (formObject.new_food_name !== ""){
ws.appendRow([formObject.new_food_name,
smartpointsServing,
formObject.serving_size_no,
formObject.serving_size_unit,
formObject.calories,
formObject.satfat,
formObject.sugar,
formObject.protein]);
ws2.appendRow([formObject.today,
newFoodHp,
formObject.food_name,
formObject.quantity]);}
else {
ws2.appendRow([formObject.today,
formObject.smartpoints,
formObject.food_name,
formObject.quantity]);
}
}
function getSmartPoints(foodLookup){
var url = "https://docs.google.com/spreadsheets/d/1pXtOAnVJOkz1DGKir79pxoMUG85LPSfoN4SSVUk0a1k/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Foods");
var data = ws.getRange(2, 1, ws.getLastRow()-1, 2).getValues();
var foodList = data.map(function(r){ return r[0]; });
var smartpointsPerServing = data.map(function(r){ return r[1]; });
var position = foodList.indexOf(foodLookup);
if (position >-1){
return smartpointsPerServing[position];
} else {
return 'Food Not Found';
}
}
function returnDropDownArray() {
var url = "https://docs.google.com/spreadsheets/d/1pXtOAnVJOkz1DGKir79pxoMUG85LPSfoN4SSVUk0a1k/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Foods");
var array = ws.getRange(2,1,ws.getLastRow()-1,1).getValues().sort();
Logger.log(array);
return ws.getRange(2,1,ws.getLastRow()-1,1).getValues().sort();
}
<!DOCTYPE html>
<html>
<head>
<!--Install Bootstrap-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<?!= include('JavaScript'); ?>
<style>
body {
color: blue;
}
</style>
</head>
<body>
<p id="date"></p>
<div class="container">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<h1><b>Health Points</b></h1>
<div class = "row">
<div class="col-md-2">
<label for="today">Date</label>
<input type="date" class="form-control" id="today" name="today" required>
</div>
</div>
<div class="row">
<div class="col-md-3">
<label for="food_name">Food Name:</label><br>
<select class="form-control" id="food_name" name="food_name" value="Select Food" required>
</select>
</div>
<div class="col-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="add" name="add">
<label class="form-check-label" for="flexCheckDefault">
Add New Food?
</label>
</div>
</div></div>
<div class="row">
<div class="col-md-4">
<label for="quantity">Quantity:</label><br>
<input id="quantity" type="number" step=".5" value="1" name="quantity">
</div>
</div><br>
<div class="row">
<div class="col-md-4">
<input id="smartpoints" type="text" placeholder="Health Points" name="smartpoints" readonly>
</div>
</div>
<!-- <br>
<div id="templateTotal"><p>Today's Total: <strong><?= total ?>/25</strong><br>
Points Remaining: <strong><?= remaining ?></strong></p></div> -->
<!-- Start section for adding foods -->
<div id="addfood" style="display:none;">
<br>
<div class="col-md-6">
<div class="card">
<div class="card-header">
Add a Food
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<label for="new_food_name">New Food Name:</label><br>
<input type="text" id="new_food_name" name="new_food_name">
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="serving_size_no">Serving Size #:</label>
<input type="number" id="serving_size_no" name="serving_size_no" step=".25">
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="serving_size_unit">Serving Size Unit:</label>
<input list="serving_size_unit_list" id="serving_size_unit" name="serving_size_unit">
<datalist id="serving_size_unit_list">
<option value="Cup(s)">
<option value="Ounce(s)">
<option value="Tbsp(s)">
<option value="Tsp(s)">
<option value="Gram(s)">
</datalist>
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="calories">Calories:</label>
<input type="number" id="calories" name="calories" step="1">
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="satfat">Saturated Fat:</label>
<input type="number" id="satfat" name="satfat">
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="satfat">Sugar:</label>
<input type="number" id="sugar" name="sugar">
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="protein">Protein:</label>
<input type="number" id="protein" name="protein">
</div>
</div><br>
</div>
</div>
</div></div><br>
<!-- End section for adding foods -->
<div class="col-md-4">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</form>
<div id="output"></div>
</div>
<script type="text/javascript">
document.getElementById("add").onchange = function(){
if (document.getElementById("add").checked) {
addfood.style.display = "block";
} else {
addfood.style.display = "none";
}
};
document.getElementById('food_name').onclick = function() {
var foodLookup = this.value;
google.script.run.withSuccessHandler(populateSmartpoints).getSmartPoints(foodLookup);
function populateSmartpoints(smartpointsPerServing){
var quantity = document.getElementById('quantity').value;
document.getElementById('smartpoints').value=smartpointsPerServing*quantity;
};
}
// Run function afterPageLoads once the page has loaded
document.addEventListener("DOMContentLoaded",afterPageLoads);
// Get drop down array for food names if that function is successful
function afterPageLoads() {
google.script.run.withSuccessHandler(afterDropDownArrayReturned).returnDropDownArray();
}
// Populate food name drop down with array from Google Sheets
function afterDropDownArrayReturned(arrayOfArrays) {
var item = document.getElementById("food_name");
console.log(item);
arrayOfArrays.forEach(function(r){
var option = document.createElement("option");
option.textContent = r[0];
item.appendChild(option);
});
}
// Update Smart Points if quantity is updated
document.getElementById('quantity').onchange = function() {
var sp = document.getElementById('smartpoints').value;
var quantity = document.getElementById('quantity').value;
document.getElementById('smartpoints').value=sp*quantity;
}
// Update food name if new food is added
document.getElementById('new_food_name').onchange = function() {
var newOption = document.getElementById('new_food_name').value;
if (newOption !==""){
var item = document.getElementById("food_name");
var option = document.createElement("option");
option.textContent = newOption;
item.appendChild(option);
var val = item.value;
item.value = newOption;
}
}
//Set today as the default date
n = new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("today").value = y + "-" + m + "-" + d;
//Reload Page
</script>
</body>
</html>
This will sum column B in a linked sheet to a form from row 2 to the submitted row.
function onFormSubmit(e) {
const sh=e.range.getSheet();
const vals=sh.getRange(2,2,e.range.getRow()-1).getValues().flat();
let sum=vals.reduce(function(a,c){return a+=c;},0);
Logger.log(sum);
}
Remember the trigger requires an installable trigger.

Add fields to this html form who add/edit data in a spreadsheet

I found the scripts below on this post, and I tried to figure out how to add a new column on the sheet and make it work with the html form the same way as the two columns already existing
But without success...
If someone can take the time to explain to me how to do it, it would be very nice ๐Ÿ™
The HTML /CSS side and basic JS are understandable for me but the rest stay hard to understand by myself
Here the sheet sample
Thanks !
CODE.GS
function doGet(request) {
return HtmlService.createTemplateFromFile('Form').evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* Find ID*/
function getID(IDsearch){
var url = "https://docs.google.com/spreadsheets/d/1QESrQb4rYhmr0uc7q6ptvmdmMbo0Bxp_hZrvKaobdI8/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Database");
/*set cells to plain text*/
var range = ws.getRange(1, 1, ws.getMaxRows(), ws.getMaxColumns());
range.setNumberFormat("#");
var data = ws.getRange(3, 1, ws.getLastRow(), 2).getValues();
var dataInput = data.map(function(r){return r[1];}); //ID column
var position = dataInput.indexOf(IDsearch); //index of the row where ID is
Logger.log(position);
var dataArray = ws.getRange(position+3, 1, 1, 2).getValues(); //array with data from searched ID
var clientsDataString = dataArray.toString();
var clientsDataArray = clientsDataString.split(',');
if(position > -1){
return clientsDataArray;
} else {
return position;
}
}
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/1QESrQb4rYhmr0uc7q6ptvmdmMbo0Bxp_hZrvKaobdI8/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Database");
var ranges = ws.getRange(4, 2, ws.getLastRow() - 3, 1).createTextFinder(formObject.ID).findAll();
if (ranges.length > 0) {
for (var i = 0; i < ranges.length; i++) {
ranges[i].offset(0, -1, 1, 2).setValues([[formObject.name, formObject.ID]]);
}
} else {
ws.appendRow([formObject.name, formObject.ID]);
}
}
JavaScript.html
<script>
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();
}
/* Search for ID */
document.getElementById("btn-procurar").addEventListener("click", onSearch);
function onSearch() {
var IDsearch = document.getElementById("insertID").value;
google.script.run.withSuccessHandler(populateForm).getID(IDsearch);
}
function populateForm(clientsData) {
document.getElementById("name").value = clientsData[0];
document.getElementById("ID").value = clientsData[1];
}
</script>
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="/Contact-Form-Clean.css">
<link rel="stylesheet" href="/styles.css">
<?!= include('JavaScript'); ?>
<?!= include('form-css'); ?>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="register-photo" style="padding-top: 30px;">
<div class="form-container" style="width: 695px;">
<form id="myForm" onsubmit="handleFormSubmit(this)" method="post" style="width: 720px;padding: 10px;padding-right: 20px;padding-left: 25px;">
<input class="form-control" type="text" id="name" name="name" placeholder="Name" style="width: 300px;display: inline-block;margin-bottom: 20px;">
<input class="form-control" type="number" id="ID" name="ID" placeholder="ID" style="width: 165px;display: inline-block;" required="">
<button type="submit" id="btn-submeter" onclick="return confirm('Submit?')" class="btn btn-primary btn-block" style="width: 644px;margin-bottom: 35px;">Save data</button>
<script>
document.getElementById("myForm").addEventListener("submit", myFunction);
function myFunction() {
alert("Success");
}
</script>
<div id="output"></div>
<div style="margin-bottom: 15px;padding: 5px;background-color: rgba(255,255,255,0);padding-top: 0px;border-top: double;">
<h6 class="text-left" style="margin-top: 15px;display: inline-block;width: 519px;margin-right: 20px;margin-bottom: 10px;">Search/Fetch ID</h6>
<input class="form-control" type="text" id="insertID" name="insertID" placeholder="Insert ID" style="width: 155px;display: inline-block;">
<button class="btn btn-primary" id="btn-procurar" onclick="onSearch()" type="button" style="width: 450px;margin: 10px 0px 25px 0px;padding: 6px;margin-top: 0px;margin-bottom: 0px;margin-left: 29px;">Search by ID</button>
</div>
</form>
</div>
</div>
<script src="/js/jquery-3.4.1.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
You want to put the values of "name", "ID", "address", "email" and "phone" using the HTML form.
In your updated shared Spreadsheet, 5 input tags are put.
You want to achieve this by modifying your script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In your current script, 2 values are used like [formObject.name, formObject.ID].
For this, please modify to 5 values like [formObject.name, formObject.ID, formObject.address, formObject.email, formObject.phone].
modified script
When your script is modified, it becomes as follows.
From:
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/1QESrQb4rYhmr0uc7q6ptvmdmMbo0Bxp_hZrvKaobdI8/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Database");
var ranges = ws.getRange(4, 2, ws.getLastRow() - 3, 1).createTextFinder(formObject.ID).findAll();
if (ranges.length > 0) {
for (var i = 0; i < ranges.length; i++) {
ranges[i].offset(0, -1, 1, 2).setValues([[formObject.name, formObject.ID]]);
}
} else {
ws.appendRow([formObject.name, formObject.ID]);
}
}
To:
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/1QESrQb4rYhmr0uc7q6ptvmdmMbo0Bxp_hZrvKaobdI8/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Database");
var ranges = ws.getRange(4, 2, ws.getLastRow() - 3, 1).createTextFinder(formObject.ID).findAll();
var v = [formObject.name, formObject.ID, formObject.address, formObject.email, formObject.phone]; // Added
if (ranges.length > 0) {
for (var i = 0; i < ranges.length; i++) {
ranges[i].offset(0, -1, 1, v.length).setValues([v]); // Modified
}
} else {
ws.appendRow(v); // Modified
}
}
Note:
In your updated shared Spreadsheet, type="number" is used for the input tag of phone. In this case, for example, when the value is 01 33 33 33 33 33, an error occurs because 01 33 33 33 33 33 is not the number. If you want to show 01 33 33 33 33 33, please modify to type="string".

Are the csv files generated with parseCsv stored somewhere?

I'm doing a web in google script.
I have done the following search method:
https://script.google.com/macros/s/AKfycbzxWqtu9bIhTXb2zP9fsOoFFqe3St1T1C91ZDVu747GCWxrR1c/exec
my code Codigo.gs is:
function doGet(e) {
Logger.log(Utilities.jsonStringify(e));
if(!e.parameter.page){
return HtmlService.createTemplateFromFile("Index").evaluate();
}
var template=HtmlService.createTemplateFromFile(e.parameter.page)
template.action=ScriptApp.getService().getUrl();
return template.evaluate();
return HtmlService
.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
/***************************** buscar asignado de trabajo ********************************************/
function get_AsignadoSS(k){
var sPers_asignado=k.pers_asignado;
var sReg_Asig="LIMA";
var contenido_ul="";
var spreadsheetId_r = '1ykYOd5PWP5aZEREnRIqkPMLT1pSYrcRA6mfQHl7bL4I'; // Please set the spreadsheet ID.
var targetSheet_r = 'Personal'; // Please set the sheet name.
if(sPers_asignado!="") {
var query_r = 'select A, B where ( B contains "'+sPers_asignado.toUpperCase()+'" or A contains "'+sPers_asignado.toUpperCase()+'" ) AND E = "'+sReg_Asig+'"'; // Please set the query for retrieving the values.
var ss_r = SpreadsheetApp.openById(spreadsheetId_r);
var sheetId_r = ss_r.getSheetByName(targetSheet_r).getSheetId();
var url_r = "https://docs.google.com/spreadsheets/d/" + spreadsheetId_r + "/gviz/tq?gid=" + sheetId_r + "&tqx=out:csv&tq=" + encodeURIComponent(query_r);
var res_r = UrlFetchApp.fetch(url_r, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
var row = Utilities.parseCsv(res_r.getContentText());
//https://docs.google.com/spreadsheets/d/1z4izqpus1yE6rZiqY1ttCEYA3NO3d7J3bZ4oFgQW330/gviz/tq?gid=Usuarios&tqx=out:csv&tq=encodeURIComponent('select A, B where ( B contains "li" )')
if(row.length>6){
var maximo=7;
}else{
var maximo=row.length;
}
//var contenido_ul=sCodigo_site;
var contenido_ul=contenido_ul+"<ul id='country-list' class='list-group'>";
for (var i = 1; i < maximo; i++) {
var nombre_site = row[i][1].toString();
var pasar_nom_site='"'+row[i][1].toString()+'"';
var contenido_ul=contenido_ul+"<li class='list-group-item' style='text-align: left' onClick='selectCountry("+pasar_nom_site+");'>"+nombre_site+"</li>";
}
var contenido_ul=contenido_ul+"</ul>";
}
if(sPers_asignado=="") {
var contenido_ul="";
}
return contenido_ul;
}
and my code Index.html is
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
function buscar_asignado(){
google.script.run.withSuccessHandler(get_Asignado).get_AsignadoSS(document.forms[0]);
}
function get_Asignado(data){
//alert("tt");
$("#suggesstion-box-asignado").show();
$("#suggesstion-box-asignado").html(data);
}
function selectCountry(codigo) {
$("#pers_asignado").val(codigo);
$("#suggesstion-box-asignado").hide();
}
/*----------------codigo esencial para conectar con codigo.GS----------------------*/
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);
</script>
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/fixedheader/3.1.6/css/fixedHeader.dataTables.min.css">
</head>
<body>
<div class="modal-header" style="background-color: red;color: white;padding-top:5px;padding-bottom:5px">
<CENTER><label style="font-size: 30px;font-family: monospace;font-weight: normal;color:white">ACTIVIDADES</label></CENTER>
</div>
<div id="todo_contenido"style="display:block">
<center><br><br>
<div class="modal-content" style="width:95%">
<div class="modal-body">
<form id="datosTrabajo" name="datosTrabajo">
<div class="form-group row">
<label for="pers_asignado" class="col-sm-2 col-form-label">Asignado:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="pers_asignado" name="pers_asignado" onkeyup="buscar_asignado();" placeholder="Nombre Asignado..." style="background-color: white">
<div id="suggesstion-box-asignado" style="position: absolute;z-index: 1"></div>
</div>
<label for="tipo_trabajo" class="col-sm-2 col-form-label">Tipo Trabajo:</label>
<div class="col-sm-4">
<select class="form-control" id="tipo_trabajo" name="tipo_trabajo" >
<option value="">Select Tipo Equipo:</option>
<option value="ATPs">ATPs</option>
<option value="Caceria Interferencia">Caceria Interferencia</option>
<option value="Desbalance RTWP">Desbalance RTWP</option>
<option value="Respaldo Baterias">Respaldo Baterias</option>
<option value="Site Audit">Site Audit</option>
<option value="Trabajos TX">Trabajos TX</option>
<option value="Prueba de Llamadas">Prueba de Llamadas</option>
<option value="PIM Logico">PIM Logico</option>
<option value="Administrativo">Administrativo</option>
<option value="OTROS">OTROS</option>
</select>
</div>
</div>
</form>
</div>
</div>
<br>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/responsive.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/fixedheader/3.1.6/js/dataTables.fixedHeader.min.js"></script>
</body>
</html>
Then each time a letter is entered, a new search is made. In this case the search becomes normal, since it only occurs in 100 records. But my question is whether it is every time a new query is made (every time a digit is entered). These csv files are stored somewhere. The problem I have is that I have a more extensive code, which searches 6000 records; but you are not doing the search, and there are personnel who connect to this website to enter information and are having problems.
Or will there be some other way to do this type of search in Google Script?
parseCsv() - Returns a tabular 2D array representation of a CSV string. So
var A=Utilities.parseCsv(csvdata);
sheet.getRange(1,1,A.length,A[0].length).setValues(A);
will put the data into sheet.
The csv and the 2d array's are not stored anywhere unless you stored somewhere.

Connecting to Shopify API with Apps Script

I am working on connecting to the Shopify API however the way it is structured for access is apikey:password#storename.myshopify.com
Apps script however will not allow you to use a URL with the login credentials for the UrlFetchApp.fetch function 12345:67890#storename.myshopify.com and I seem unable to pass the information through successfully via the basic headers.
function shopify_connect() {
var url = "https://storename.myshopify.com/admin/products.json/GET";
var apikey = '12345';
var password = '67890';
var headers = {
"User-Agent" :"info#website.com",
"Authentication" : 'Basic ' + Utilities.base64Encode(apikey + ':' + password)
}
var options = {
"headers": headers,
}
var response = UrlFetchApp.fetch(url, options);
}
When I log the output from response, it appears that I am getting to the login HTML however never passing beyond that.
Any help in clarifying this access method would be greatly appreciated.
Logger Response:
[19-01-01 12:09:54:516 EST] <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Shopify ยป Please log in</title>
<meta name="referrer" content="never" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="icon" sizes="192x192" href="//cdn.shopify.com/s/assets/touch-icons/touch-icon-192x192-840b11274adbc510a1db23976759bd31ceee84ddbb36478d494a3a2cf19b5ae6.png" />
<link rel="shortcut icon" type="image/x-icon" href="//cdn.shopify.com/s/assets/favicon-4425e7970f1327bc362265f54e8c9c6a4e96385b3987760637977078e28ffe92.png" />
<link rel="apple-touch-startup-image" href="//cdn.shopify.com/s/assets/touch-icons/mobile-startup-564eed49b6c483b80796f529e05b4bf1d54e9cd9beeb0bb89b10d3c6a2282ea6.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="//cdn.shopify.com/s/assets/touch-icons/icon-114x114-precomposed-79d1c57f01b233f016319dc4048d90524e9ce252c058a306ef9db2216ab26911.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="//cdn.shopify.com/s/assets/touch-icons/icon-72x72-precomposed-584c35aa679456ab4e2f1cd971191498d7fecf7321b4ded8bae5c5a2c51176e3.png" />
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="//cdn.shopify.com/s/assets/touch-icons/icon-57x57-precomposed-49c0927bd56de30bc28439aed87097b7c8e41f2bb4f00661f01a00729c2a1b77.png" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=0" />
<link rel="stylesheet" media="screen" href="//cdn.shopify.com/s/assets/dialog-fresh-66526625df0ed5b32afd82a4e7ae3a843a721051c14cdf0f5add5ea1e7988b07.css" crossorigin="anonymous" data-turbolinks-track="true" integrity="sha256-ZlJmJd8O1bMq/YKk5646hDpyEFHBTN8PWt1eoeeYiwc=" />
</head>
<body class="page-auth-login fresh-ui">
<div id="container">
<noscript class="no-js">
In order to use the Shopify admin you need to enable Javascript. <a target="_blank" href="https://www.enable-javascript.com/">Learn how to enable Javascript</a>.
</noscript>
<main role="main" id="dialog-alternate">
<div class="login-form">
<h1 class="dialog-heading">Runeworks Development</h1>
<h2 class="dialog-subheading">Log in to manage your store</h2>
<form class="lookup-form" action="/admin/auth/login" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="โœ“" /><input type="hidden" name="authenticity_token" value="o+iwLU/BJDawX3A5Pnpa9S0MCn7CIdhzXoPqXvJoiizZp6sK4FRsLRo6IIAUUAJI5mUgIoFyOpSNqswZJfKRdg==" />
<div id="email-login">
<div class="clearfix">
<div class="login-container">
<div class="lform dialog-form">
<div class="require-cookies">
<div class="ui-banner ui-banner--status-critical ui-banner--within-page">
<div class="ui-banner__ribbon"><svg class="next-icon next-icon--size-20 next-icon--no-nudge" aria-hidden="true" focusable="false"> <use xlink:href="#error-major" /> </svg></div><div class="ui-banner__content-container"><div class="ui-banner__heading"><h2 class="ui-heading">Please enable cookies in your browser preferences to continue.</h2></div></div></div> </div>
</div>
<div id="sign-in-form" class="lform dialog-form">
<input type="hidden" name="redirect" value="" id="redirect" />
<input type="hidden" name="step" value="lookup" />
<div id="login">
<div class="input-group">
<div class="next-input-wrapper"><label class="next-label" for="Login">Email</label><input type="email" name="login" id="Login" spellcheck="false" autofocus="autofocus" required="required" class="next-input" /></div>
<div class="next-input-wrapper"><label class="next-label helper--visually-hidden" for="Password">Password</label><input type="password" name="password" id="Password" class="next-input hidden-password" tabindex="-1" placeholder="Password" spellcheck="false" /></div>
</div>
</div> <!-- /#login -->
<button class="ui-button ui-button--primary ui-button--full-width dialog-submit" type="submit" name="commit" id="EmailConfirm">Continue</button>
</div> <!-- /#sign-in-form -->
<div id="remember-me" class="remember-me">
<input type="hidden" name="remember" id="remember_checkbox_default" value="0" />
<div class="next-input-wrapper"><label class="next-label next-label--switch" for="remember_checkbox">Keep me logged in</label><input type="checkbox" name="remember" id="remember_checkbox" value="1" class="next-checkbox" checked="checked" /><span class="next-checkbox--styled"><svg class="next-icon next-icon--size-10 checkmark" aria-hidden="true" focusable="false"> <use xlink:href="#next-checkmark-thick" /> </svg></span></div>
</div>
</div>
</div>
</div>
<div id="other-login">
</div>
</form>
<script type="text/javascript">
if (typeof window.analytics !== 'undefined') {
window.analytics.trackForm($('[action="/admin/auth/login"]')[0], 'login', {
category: 'login',
subdomain: "runeworks-development.myshopify.com"
});
}
if (!navigator.cookieEnabled) {
$('.require-cookies').show();
}
var showContinueButton = document.querySelector('.email-login a');
if (showContinueButton instanceof HTMLElement) {
showContinueButton.addEventListener('click', showLoginWithEmailBox.bind(this, true));
}
function showLoginWithEmailBox(show) {
var continueButton = document.querySelector('.dialog-submit');
var display = show ? '' : 'none';
document.getElementById('login').style.display = display;
if (continueButton instanceof HTMLElement) {
continueButton.style.display = display;
}
if (showContinueButton instanceof HTMLElement) {
showContinueButton.style.display = show ? 'none' : '';
}
}
(function (){
var ssoEnabled = false;
if (ssoEnabled) {
showLoginWithEmailBox(false)
}
})();
</script>
</div>
</main>
<footer role="contentinfo" id="footer">
<a target="_blank" class="ico ico-shopify-bag" href="//www.shopify.com">
<span class="helper--visually-hidden">Shopify.com</span>
</a> </footer>
</div>
<script src="//cdn.shopify.com/s/assets/admin/admin_jquery-1f0f820501c3b7fcb70379d8fa17d2fcfdb3722abc2a5eeedac0f05bfef7705c.js" crossorigin="anonymous" integrity="sha256-Hw+CBQHDt/y3A3nY+hfS/P2zciq8Kl7u2sDwW/73cFw="></script>
<script src="//cdn.shopify.com/s/assets/admin/auth-af2f48596342908db2529c61a0cfcb59fa7feff59591946bdd8caad81b7abc64.js" crossorigin="anonymous" integrity="sha256-ry9IWWNCkI2yUpxhoM/LWfp/7/WVkZRr3Yyq2Bt6vGQ="></script>
<script>var _gaq = _gaq || [];_gaq.push(["_setAccount","UA-82702-18"]);_gaq.push(["_addDevId","o5cUG"]);_gaq.push(["_setAllowLinker",true]);_gaq.push(["_setDomainName",".myshopify.com"]);_gaq.push(["_setAllowHash",false]);_gaq.push(["_trackPageview","\/admin\/auth\/login"]);</script>
<script id="TrekkieLoader" type="text/javascript">
(function(){
var config = {"Trekkie":{"appName":"admin","development":false,"embedMode":"parent","defaultAttributes":{"shopId":16037216320,"requestIsFromShopify":false}},"Clickstream":{"appName":"admin"},"Performance":{"navigationTimingApiMeasurementsEnabled":true,"navigationTimingApiMeasurementsSampleRate":0.25},"Session Attribution":{},"LastShop":{}};
var trekkie_version = '2017.09.05.1';
var analytics = window.analytics = window.analytics || [];
if (analytics.integrations) {
return;
}
analytics.methods = [
'identify',
'page',
'ready',
'track',
'trackForm',
'trackLink'
];
analytics.factory = function(method) {
return function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(method);
analytics.push(args);
return analytics;
};
};
for (var i = 0; i < analytics.methods.length; i++) {
var key = analytics.methods[i];
analytics[key] = analytics.factory(key);
}
analyt
So after working with it further, taking another look at the example Cooper referenced, I was able to get the connection to process correctly.
Here is the code in the event that someone else has the same issue in the future:
function shopify_connection_test() {
var api_key = '<enter api key here';
var api_pass = '<enter api password here>';
var store_url = 'https://storename.myshopify.com/admin/products.json';
var product = {
"product": {
"title": "Burton Custom Freestyle 151",
"body_html": "<strong>Good snowboard!</strong>",
"vendor": "Burton",
"product_type": "Snowboard",
"tags": "Barnes & Noble, John's Fav, \"Big Air\""
}
}
var payload = JSON.stringify(product);
var headers = {
"Content-Type" : "application/json",
"Authorization": "Basic " + Utilities.base64Encode(api_key + ":" + api_pass)
};
var params = {
"method" : "POST",
"headers" : headers,
"contentType" : "application/json",
"payload" : payload
}
var response = UrlFetchApp.fetch(store_url, params)
Logger.log(response.getContentText())
}
This specifically uploads a product, I didn't want to exclude any information. The references in the Shopify API documentation should be enough for anyone looking to change its overall functionality.
I had a similar problem where Shopify would return a (401) unauthorized {"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"} when using UrlFetchApp on GAS, even though the request was working perfectly with Postman.
Runeworks Gaming solution worked, the trick is to pass the authorization into a "headers" object, nested in the "params" of the url fetch app.
I have used UrlFetchApp on many other occasions by putting the "Authorization" header directly into the params, but apparently, this won't work with Shopify.
Working:
var SHOP_ID = "Your shop ID";
var API_KEY = "Your API key";
var API_PASSWORD = "Your API password";
var encoded = Utilities.base64Encode(API_KEY + ':' + API_PASSWORD);
var headers = {
"Content-Type" : "application/json",
"Authorization": "Basic " + encoded
};
var options = {
"contentType" : "application/json",
'method' : 'GET',
'headers' : headers, // This is the important part
'followRedirects' : false,
};
var response = UrlFetchApp.fetch("https://" + SHOP_ID + ".myshopify.com/admin/api/2019-04/orders.json?status=any",options);
var RESPONSE_CODE = response.getResponseCode();
var CONTENT_JSON = JSON.parse(response.getContentText());