avatarNibesh Khadka

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

23566

Abstract

umber">0</span>, <span class="hljs-number">2</span>)) < <span class="hljs-number">9</span> || <span class="hljs-title class_">Number</span>(e.<span class="hljs-property">target</span>.<span class="hljs-property">value</span>.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>)) > <span class="hljs-number">17</span>) { timeWarningText.<span class="hljs-title function_">css</span>(<span class="hljs-string">'color'</span>, <span class="hljs-string">'red'</span>); } <span class="hljs-keyword">else</span> { timeWarningText.<span class="hljs-title function_">css</span>(<span class="hljs-string">'color'</span>, <span class="hljs-string">''</span>); } });

<span class="hljs-comment">//  disable button unless agreed to terms and conditions as well as all fields are filled.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">handleButtonClick</span>(<span class="hljs-params">e</span>) {
   <span class="hljs-keyword">if</span> (name.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || address.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || email.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || company.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || date.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || time.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || purpose.<span class="hljs-title function_">val</span>().<span class="hljs-title function_">trim</span>() === <span class="hljs-string">"You need me to"</span> || !termsAndConditions.<span class="hljs-title function_">is</span>(<span class="hljs-string">":checked"</span>)) {
        <span class="hljs-title function_">alert</span>(<span class="hljs-string">"Please fill in all input boxes"</span>);
        e.<span class="hljs-title function_">preventDefault</span>(); <span class="hljs-comment">// don't reload</span>
    }
    <span class="hljs-keyword">else</span> {
     <span class="hljs-comment">// for now let's just console log a message</span>
        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"All data are valid. They can be submitted to the backend."</span>)
       e.<span class="hljs-title function_">preventDefault</span>();
    }
}
submitButton.<span class="hljs-title function_">click</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) { <span class="hljs-title function_">handleButtonClick</span>(e); });

});</pre></div><p id="a319">The form validation will detect empty fields, warn the user of invalid dates or times, and disable submission on empty fields. Also, we’ve made sure that any date before today can’t be selected. Validation is very basic, the project’s main focus is creating an automatic ecosystem using Google Workspace, not front-end development.</p><p id="5263">Next, we’ll connect the form with the backend. This involves implementing a backend script to handle form submissions, establishing a connection between the front end and the backend, submitting form data to the backend on submission, and storing appointment details in Google Sheets.</p><h1 id="dcb6">Using Google Spreadsheet as a Database</h1><h1 id="a7c4">Coding Remotely In VS Code With Clasp</h1><p id="217d">Let’s first go to Google Drive and create a Google Sheets. You can download the one I’m using from the <a href="https://github.com/nibukdk/AppointmentFormAutomationGoogleAppsScriptTutorial/tree/main/assets">assets</a> folder in the GitHub repo. Then create a <a href="https://developers.google.com/apps-script/guides/bound">bound script</a> from the spreadsheet’s tab.</p><figure id="b6bb"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*DPryWtJQw_u7KzYi.png"><figcaption></figcaption></figure><p id="cb92">To pull this project into our local directory we’ll use clasp. If you don’t have the <a href="https://www.npmjs.com/package/@google/clasp">clasp</a> installed then check out my <a href="https://readmedium.com/how-to-write-google-apps-script-code-locally-in-your-favorite-ide-de875ea5f2f7">tutorial</a> on using clasp with VS code. We’ll need Project Script ID to link our remote project to this cloud project. It can be found in our Apps Script project from <b>Project Settings>Project ID</b>.</p><figure id="5fb3"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*djSU92kfrU90rulN.png"><figcaption></figcaption></figure><p id="a79e">After that in the command line inside of the project directory use this command to clone the project there.</p><div id="815b"><pre>clasp <span class="hljs-built_in">clone</span> <span class="hljs-string">"YOUR PROJECT ID"</span> --rootDir .</pre></div><p id="909e">The period, “.”, is for the current directory if you’re not inside the project folder make sure to provide a proper path instead.</p><h1 id="03a0">Establishing a Connection between Frontend and Backend</h1><p id="4fbf">Now, we’ll work on establishing communication between HTML form and Google Spreadsheet. For that let’s make some changes in our index.js file inside the frontend folder.</p><p id="679c">First, we’ll define <b>BASE_URL</b> which will be the URL address that we’ll use as API to call the backend. Its value is the URL we get after deploying our Apps Script as a Web App later on. We’ll also define the basic payload(options) that’ll be part of the JS <a href="https://developer.mozilla.org/en-US/docs/Web/API/fetch#examples">fetch</a> method.</p><div id="e718"><pre><span class="hljs-keyword">const</span> <span class="hljs-variable constant_">BASE_URL</span> = <span class="hljs-string">""</span>; <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">PAYLOAD</span> = { <span class="hljs-attr">method</span>: <span class="hljs-string">"GET"</span>, <span class="hljs-attr">redirect</span>: <span class="hljs-string">"follow"</span>, <span class="hljs-attr">headers</span>: { <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"text/plain;charset=UTF-8"</span>, }, };</pre></div><p id="de00">We’ll pass all the values of input fields in the HTML form as a query string. We’ll implement a function called <b>convertPayloadToUrlEncodes</b>() to effectively convert the key-value pairs extracted from the HTML form into a standardized query string format</p><div id="dacb"><pre><span class="hljs-comment">// convert from {name:Nibesh, address:Helsinki} to name=Nibesh&address=Helsinki</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">convertPayloadToUrlEncodes</span>(<span class="hljs-params">params = {}</span>) { <span class="hljs-keyword">return</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">entries</span>(params) .<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">[key, value]</span>) =></span> [<span class="hljs-built_in">encodeURIComponent</span>(key), <span class="hljs-built_in">encodeURIComponent</span>(value)].<span class="hljs-title function_">join</span>(<span class="hljs-string">'='</span>)) .<span class="hljs-title function_">join</span>(<span class="hljs-string">'&'</span>); };</pre></div><p id="627b">Now let’s write code for the function that’ll be making HTTP requests to the spreadsheet.</p><div id="04a3"><pre><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">fetchData</span>(<span class="hljs-params">params = { reqType: <span class="hljs-string">"nothing"</span> }</span>) { <span class="hljs-comment">// modify url </span> <span class="hljs-keyword">const</span> url = <span class="hljs-string"><span class="hljs-subst">${BASE_URL}</span>?<span class="hljs-subst">${convertPayloadToUrlEncodes(params)}</span></span>;

<span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(url, <span class="hljs-variable constant_">PAYLOAD</span>);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.<span class="hljs-title function_">json</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data)

}</pre></div><p id="a218">Apps Script does not support standard request protocols like POST, GET, PUT, or DELETE. Instead, we must utilize a unique identifier, ‘<b>reqType</b>’ in this instance, to determine the appropriate function to execute. This approach will be mirrored in the backend codebase, where a switch case mechanism will handle such requests. For now, it’s crucial to understand that the ‘<b>nothing</b>’ reqType signifies a connection check, not any data manipulation. Additionally, given the lack of front-end actions beyond logging, we will simply record the data returned by the backend.</p><p id="8810">Next, let’s change the <b>else</b> block of our <b>handleButtonClick()</b> function.</p><div id="4e76"><pre><span class="hljs-keyword">else</span> { <span class="hljs-title function_">fetchData</span>() e.<span class="hljs-title function_">preventDefault</span>(); }</pre></div><p id="8a8c">We’re not passing any values for now because we only want to check if the connection works. With all this is what our <b>index.js</b> file looks like.</p><div id="3e78"><pre><span class="hljs-keyword">const</span> <span class="hljs-variable constant_">BASE_URL</span> = <span class="hljs-string">""</span>; <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">PAYLOAD</span> = { <span class="hljs-attr">method</span>: <span class="hljs-string">"GET"</span>, <span class="hljs-attr">redirect</span>: <span class="hljs-string">"follow"</span>, <span class="hljs-attr">headers</span>: { <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"text/plain;charset=UTF-8"</span>, }, }; <span class="hljs-keyword">function</span> <span class="hljs-title function_">convertPayloadToUrlEncodes</span>(<span class="hljs-params">params = {}</span>) { <span class="hljs-keyword">return</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">entries</span>(params) .<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">[key, value]</span>) =></span> [<span class="hljs-built_in">encodeURIComponent</span>(key), <span class="hljs-built_in">encodeURIComponent</span>(value)].<span class="hljs-title function_">join</span>(<span class="hljs-string">'='</span>)) .<span class="hljs-title function_">join</span>(<span class="hljs-string">'&'</span>); }; <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">fetchData</span>(<span class="hljs-params">params = { reqType: <span class="hljs-string">"nothing"</span> }</span>) { <span class="hljs-keyword">const</span> url = <span class="hljs-string"><span class="hljs-subst">${BASE_URL}</span>?<span class="hljs-subst">${convertPayloadToUrlEncodes(params)}</span></span>;

<span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(url, <span class="hljs-variable constant_">PAYLOAD</span>);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.<span class="hljs-title function_">json</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data)

}

(<span class="hljs-variable language_">document</span>).<span class="hljs-title function_">ready</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) { <span class="hljs-keyword">let</span> name = (<span class="hljs-string">"#name"</span>); <span class="hljs-keyword">let</span> email = (<span class="hljs-string">"#email"</span>); <span class="hljs-keyword">let</span> address = (<span class="hljs-string">"#address"</span>); <span class="hljs-keyword">let</span> company = (<span class="hljs-string">"#company"</span>); <span class="hljs-keyword">let</span> date = (<span class="hljs-string">"#date"</span>); <span class="hljs-keyword">let</span> time = (<span class="hljs-string">"#time"</span>); <span class="hljs-keyword">let</span> purpose = (<span class="hljs-string">"select"</span>); <span class="hljs-keyword">let</span> message = (<span class="hljs-string">"#messageArea"</span>); <span class="hljs-keyword">let</span> dateWarningText = (<span class="hljs-string">'#dateHelp'</span>); <span class="hljs-keyword">let</span> timeWarningText = (<span class="hljs-string">'#timeHelp'</span>); <span class="hljs-keyword">let</span> submitButton = (<span class="hljs-string">'#submit'</span>); <span class="hljs-keyword">let</span> termsAndConditions = $(<span class="hljs-string">'#termsAndConditions'</span>); <span class="hljs-comment">// set min date value to today</span> <span class="hljs-keyword">let</span> today = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>().<span class="hljs-title function_">toISOString</span>().<span class="hljs-title function_">split</span>(<span class="hljs-string">'T'</span>)[<span class="hljs-number">0</span>]; <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementsByName</span>(<span class="hljs-string">"date"</span>)[<span class="hljs-number">0</span>].<span class="hljs-title function_">setAttribute</span>(<span class="hljs-string">'min'</span>, today);

$(<span class="hljs-string">'#date'</span>).<span class="hljs-title function_">change</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) {
    <span class="hljs-keyword">var</span> d = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(e.<span class="hljs-property">target</span>.<span class="hljs-property">value</span>)
    <span class="hljs-comment">// warn if sunday or saturday</span>
    <span class="hljs-keyword">if</span> (d.<span class="hljs-title function_">getDay</span>() === <span class="hljs-number">0</span> || d.<span class="hljs-title function_">getDay</span>() === <span class="hljs-number">6</span>) {
        dateWarningText.<span class="hljs-title function_">css</span>(<span class="hljs-string">'color'</span>, <span class="hljs-string">'red'</span>);

        $(<span class="hljs-string">'#date'</span>).<span class="hljs-title function_">after</span>(dateWarningText);
    } <span class="hljs-keyword">else</span> {
        dateWarningText.<span class="hljs-title function_">css</span>(<span class="hljs-string">'color'</span>, <span class="hljs-string">""</span>)
    }
})

<span class="hljs-comment">// time</span>
$(<span class="hljs-string">'#time'</span>).<span class="hljs-title function_">change</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementsByName</span>(<span class="hljs-string">"time"</span>)[<span class="hljs-number">0</span>].<span class="hljs-property">value</span>.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>));
    <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Number</span>(e.<span class="hljs-property">target</span>.<span class="hljs-property">value</span>.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>)) &lt; <span class="hljs-number">9</span> || <span class="hljs-title class_">Number</span>(e.<span class="hljs-property">target</span>.<span class="hljs-property">value</span>.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>)) &gt; <span class="hljs-number">17</span>) {
        timeWarningText.<span class="hljs-title function_">css</span>(<span class="hljs-string">'color'</span>, <span class="hljs-string">'red'</span>);
    }
    <span class="hljs-keyword">else</span> {
        timeWarningText.<span class="hljs-title function_">css</span>(<span class="hljs-string">'color'</span>, <span class="hljs-string">''</span>);
    }
});

<span class="hljs-comment">//  disable button unless agreed to terms and conditions as well as all fields are filled.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">handleButtonClick</span>(<span class="hljs-params">e</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"handleButtonClick is called"</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name.<span class="hljs-title function_">val</span>());
    <span class="hljs-keyword">if</span> (name.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || address.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || email.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || company.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || date.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || time.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || purpose.<span class="hljs-title function_">val</span>().<span class="hljs-title function_">trim</span>() === <span class="hljs-string">"You need me to"</span> || !termsAndConditions.<span class="hljs-title function_">is</span>(<span class="hljs-string">":checked"</span>)) {
        <span class="hljs-title function_">alert</span>(<span class="hljs-string">"Please fill in all input boxes"</span>);
        e.<span class="hljs-title function_">preventDefault</span>(); <span class="hljs-comment">// don't reload</span>
    }
    <span class="hljs-keyword">else</span> {
       
        <span class="hljs-title function_">fetchData</span>()
        e.<span class="hljs-title function_">preventDefault</span>();
    }
}
submitButton.<span class="hljs-title function_">click</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) { <span class="hljs-title function_">handleButtonClick</span>(e); });

});</pre></div><h2 id="6f71">Web App and DoGet() or DoPost()</h2><p id="c419">Before we write server-side code. Let’s briefly understand how exactly does connection is established as a <a href="https://developers.google.com/apps-script/guides/web">Web App</a> in an app script project. Apps Script provides two methods for this DoGet and DoPost. We can use either of them. These two are the method that receives the requests from the front end.</p><p id="f808">Both of these functions provide access to a JS object, “<b>e</b>” as mentioned in the documentation. This parameter provides access to the query strings that we’ll pass in <b>fetchData()</b> as part of the URL, returned by the <b>convertPayloadToUrlEncodes()</b> function. Each parameter can be accessed from the <b>parameter</b> JS object inside the <b>e</b> parameter. For instance: The values in the <code>https://script.google.com/.../exec?username=jsmith&amp;age=21</code> URL can be accessed as <code>e.parameter.name</code> and <code>e.parameter.age</code>.</p><h1 id="2cfc">Create an API with Apps Script</h1><p id="8a5c">Now let’s get back to our project. We’ll create a new file “<b>api.js</b>” inside of our backend folder in VS code.</p><div id="4354"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">doGet</span>(<span class="hljs-params">e</span>) { <span class="hljs-keyword">try</span> { <span class="hljs-keyword">var</span> reqType = e.<span class="hljs-property">parameter</span>.<span class="hljs-property">reqType</span>; <span class="hljs-keyword">var</span> param = e.<span class="hljs-property">parameter</span>;

    <span class="hljs-keyword">switch</span> (reqType) {
            
                <span class="hljs-attr">default</span>:
                    <span class="hljs-keyword">return</span> <span class="hljs-title function_">contentService</span>({
                        <span class="hljs-attr">status</span>: <span class="hljs-number">200</span>,
                        <span class="hljs-attr">message</span>: <span class="hljs-string">"Connection Successfull"</span>,
                        <span class="hljs-attr">data</span>: <span class="hljs-string">""</span>,
                    });
            }
  } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-title function_">contentService</span>({
            <span class="hljs-attr">status</span>: <span class="hljs-number">400</span>,
            <span class="hljs-attr">message</span>: <span class="hljs-string">"Error"</span>,
            <span class="hljs-attr">data</span>: err,
        });
    }
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">contentService</span>(<span class="hljs-params">data</span>) { <span class="hljs-keyword">return</span> <span class="hljs-title class_">ContentService</span>.<span class="hljs-title function_">createTextOutput</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data)).<span class="hljs-title function_">setMimeType</span>( <span class="hljs-title class_">ContentService</span>.<span class="hljs-property">MimeType</span>.<span class="hljs-property">JSON</span> ); }</pre></div><p id="2c5a">As I’ve already mentioned we’ll be using the query string <b>reqType</b> as the keyword to switch the API request. Since now we’re just establishing a connection we’ll only define the default switch case and return a connection successful message. We’ll also define error just in case.</p><p id="5baf"><a href="https://developers.google.com/apps-script/guides/content">ContentService</a> in Apps Script can b

Options

e used to return the output as JSON like I’m doing here.</p><p id="79de"><i>If you’re using the DoPost() instead of the DoGet() method, make sure to change the method from “GET” to “Post” in index.js’s Payload, or else you can’t establish a connection.</i></p><p id="07e8">Now, we’ll have to push changes from VS code to the cloud. Before that, I’ll create another file, .claspignore, in our root directory and frontend folder’s path there, because I don’t need a frontend folder in my apps script project.</p><div id="1a84"><pre><span class="hljs-strong">/frontend/</span></pre></div><p id="1908">Now push the backend folder to the cloud with the command <code>clasp push</code> .</p><h2 id="1fc9">Deploying the App Script Project and Acquiring URL</h2><p id="41c2">Remember our <code>BASE_URL</code> is still empty. Before pushing changes to the cloud project, we must deploy the web app to make it accessible online. This deployment process generates a unique URL as the entry point for accessing the web app. We'll need to capture this URL to establish a proper connection from the front. Let's deploy our script as a Web App.</p><ol><li>Go to the apps script project in the cloud and click on the deploy button in the top right corner.</li><li>On the popup window:</li><li>Select Web App</li><li>Select “Anyone” for <b>Who has access?</b> dropdown</li><li>Deploy the project</li><li>Copy the script URL and paste it as the value for <code>BASE_URL</code>.</li></ol><figure id="fe7d"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*MWBR5vTJVsJP8fbg.png"><figcaption></figcaption></figure><p id="e002">After saving everything load the HTML file in the browser fill in every input field and submit the data. The console of the browser should have logged the connection established message.</p><figure id="110f"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*KL1JqR2LQe4n_Qj0.png"><figcaption></figcaption></figure><h2 id="4628">Centralized Storage for Project IDs and API Keys</h2><p id="07c8">Before we start coding to save the data to the spreadsheet let’s first create a configuration file, named <b>cofig.js</b>. It’ll be a file where we’ll save our ID for various files and folders, from Google Drive that are part of this project. We’ll also save the API key of ChatGPT here.</p><div id="a7b1"><pre><span class="hljs-keyword">var</span> <span class="hljs-variable constant_">GPT_SECRET_KEY</span> = <span class="hljs-string">""</span>; <span class="hljs-comment">// gpt secert key</span> <span class="hljs-keyword">var</span> <span class="hljs-variable constant_">FORM_FOLDER_ID</span> = <span class="hljs-string">""</span>;<span class="hljs-comment">// folder to store forms created from questions</span> <span class="hljs-keyword">var</span> <span class="hljs-variable constant_">DOCS_FOLDER_ID</span> = <span class="hljs-string">""</span>;<span class="hljs-comment">// folders to store docs ceated from user's response to the forms</span> <span class="hljs-keyword">var</span> <span class="hljs-variable constant_">TEMPLATE_ID</span> = <span class="hljs-string">""</span>;<span class="hljs-comment">// ID for the template used to create Docs</span> <span class="hljs-keyword">var</span> <span class="hljs-variable constant_">APPOINTMENT_CALENDAR_ID</span> = <span class="hljs-string">""</span>; <span class="hljs-comment">// id for Google Calendar used to notify for calendar</span> <span class="hljs-keyword">var</span> <span class="hljs-variable constant_">MARK_REVIEWED_IMAGE_LINK_ID</span> = <span class="hljs-string">""</span>; <span class="hljs-comment">// id for the image that'll be embedded into the docs</span> <span class="hljs-keyword">var</span> <span class="hljs-variable constant_">SCRIPT_URL</span> = <span class="hljs-string">""</span>; <span class="hljs-comment">// URL returend after deploying the script as web app.</span></pre></div><p id="a465"><i>Read comments for the purpose creation of each variable.</i></p><p id="32f6">Create Folders and Files that are necessary for this project into your Google Drive. Mine looks like the image given below. You can download images and templates from the <a href="https://github.com/nibukdk/AppointmentFormAutomationGoogleAppsScriptTutorial/tree/main/assets">assets</a> folder in the GitHub repo.</p><figure id="0988"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*x95AGcRIeoe9s_QP.png"><figcaption></figcaption></figure><p id="e2bf">You can get Folder’s and Doc’s ID from its URL after opening it as shown in the image below.</p><figure id="6fdf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*zia0HIghu7VsHASw.png"><figcaption></figcaption></figure><p id="7bc1">To get IDs from files like PDF, images, etc, First, get the shareable link and then copy the highlighted section as shown in the image below.</p><figure id="fa0b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*rASQOlIhPLWl-EQq.png"><figcaption></figcaption></figure><p id="1953">To get or create the Secret Key for the Chat GPT, go to your profile on <a href="https://openai.com/">OpenAi.com</a> and follow the instructions in the image below.</p><figure id="e717"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*qKgDlDYdW1okGnHW.png"><figcaption></figcaption></figure><p id="39fb">For URL leave it empty cause we don’t need it now.</p><p id="e78b">Make sure to save all those values and push the changes to the cloud with a clasp.</p><p id="a83c"><b><i>Utilizing the <code>var</code> keyword for variable declaration instead of <code>let</code> or <code>const</code> ensures global accessibility from other files within the project.</i></b></p><p id="9a60"><i>Additionally, you’ll find the config_4_tutorial.js file instead of the config.js file in the GitHub repo, ensuring its confidentiality</i>.</p><h1 id="1bc7">Saving HTML Form Into Google Sheets</h1><p id="ec40">Now, let’s save the data to the spreadsheet. For that make the following changes inside the switch method of the api.js file.</p><div id="0ed5"><pre><span class="hljs-comment">//...... continue </span> <span class="hljs-keyword">switch</span> (reqType) { <span class="hljs-keyword">case</span> <span class="hljs-string">"updateAppointment"</span>: <span class="hljs-keyword">const</span> newAppointmentData = { ...fakeAppointmentData }; newAppointmentData.<span class="hljs-property">name</span> = param.<span class="hljs-property">name</span>; newAppointmentData.<span class="hljs-property">email</span> = param.<span class="hljs-property">email</span>; newAppointmentData.<span class="hljs-property">address</span> = param.<span class="hljs-property">address</span>; newAppointmentData.<span class="hljs-property">company</span> = param.<span class="hljs-property">company</span>; newAppointmentData.<span class="hljs-property">purpose</span> = param.<span class="hljs-property">purpose</span>; newAppointmentData.<span class="hljs-property">date</span> = param.<span class="hljs-property">date</span>; newAppointmentData.<span class="hljs-property">time</span> = param.<span class="hljs-property">time</span>; newAppointmentData.<span class="hljs-property">message</span> = param.<span class="hljs-property">message</span>;

      <span class="hljs-keyword">return</span> <span class="hljs-title function_">contentService</span>(<span class="hljs-title function_">updateAppointmentDataInSheets</span>(newAppointmentData));

<span class="hljs-comment">// continue ...</span></pre></div><p id="d11f">We’re using the <b>reqType</b> <code>updateAppointment</code> as keyword here. We'll have to pass this same keyword in our index.js file later on. If the condition is satisfied we call the function <code>updateAppointmentDataInSheets()</code> and pass the values as JS object. We'll create this function and <code>fakeAppointmentData</code> JS object inside a new file <b>sheet.js</b> in the backend folder.</p><div id="1084"><pre><span class="hljs-keyword">var</span> ss = <span class="hljs-title class_">SpreadsheetApp</span>.<span class="hljs-title function_">getActiveSpreadsheet</span>(); <span class="hljs-comment">// all data except the timestamp</span> <span class="hljs-keyword">var</span> fakeAppointmentData = { <span class="hljs-attr">email</span>: <span class="hljs-string">"[email protected]"</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Arttu Karjalainen"</span>, <span class="hljs-attr">address</span>: <span class="hljs-string">"Helsinki"</span>, <span class="hljs-attr">company</span>: <span class="hljs-string">"Himali Coders"</span>, <span class="hljs-attr">date</span>: <span class="hljs-string">"2023-10-19"</span>, <span class="hljs-attr">time</span>: <span class="hljs-string">"10:00"</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">"An issue with the script needs fixing. It was working fine, but then I changed ownership of some google folders (since I'm using the later for work typically so it's more convenient to have everything owned by that account). Now we're seeing attached error 'access denied driveapp' on execute population."</span>, <span class="hljs-attr">purpose</span>: <span class="hljs-string">"Review Code"</span>, }

<span class="hljs-keyword">function</span> <span class="hljs-title function_">updateAppointmentDataInSheets</span>(<span class="hljs-params">appointmentData = fakeAppointmentData</span>) { <span class="hljs-keyword">try</span> { <span class="hljs-keyword">const</span> sheet = ss.<span class="hljs-title function_">getSheetByName</span>(<span class="hljs-string">"Appointments"</span>); <span class="hljs-keyword">const</span> data = sheet.<span class="hljs-title function_">getDataRange</span>().<span class="hljs-title function_">getValues</span>(); <span class="hljs-keyword">const</span> currentTimeStamp = <span class="hljs-title function_">getReadableDate</span>();

<span class="hljs-keyword">if</span> (data.<span class="hljs-property">length</span> === <span class="hljs-number">1</span>) {
  data.<span class="hljs-title function_">push</span>([currentTimeStamp, appointmentData.<span class="hljs-property">name</span>, appointmentData.<span class="hljs-property">email</span>, appointmentData.<span class="hljs-property">address</span>, appointmentData.<span class="hljs-property">company</span>, appointmentData.<span class="hljs-property">purpose</span>, appointmentData.<span class="hljs-property">date</span>, appointmentData.<span class="hljs-property">time</span>, appointmentData.<span class="hljs-property">message</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>])
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt; data.<span class="hljs-property">length</span>; i++) {
    <span class="hljs-comment">// if name, email and time-stamp </span>
    <span class="hljs-keyword">if</span> (data[i][<span class="hljs-number">0</span>].<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>) === currentTimeStamp.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>) &amp;&amp; data[i][<span class="hljs-number">1</span>] === appointmentData.<span class="hljs-property">name</span> &amp;&amp; data[i][<span class="hljs-number">2</span>] === appointmentData.<span class="hljs-property">email</span>) {
      data[i][<span class="hljs-number">0</span>] = currentTimeStamp;
      data[i][<span class="hljs-number">3</span>] = appointmentData.<span class="hljs-property">address</span>;
      data[i][<span class="hljs-number">4</span>] = appointmentData.<span class="hljs-property">company</span>;
      data[i][<span class="hljs-number">5</span>] = appointmentData.<span class="hljs-property">purpose</span>;
      data[i][<span class="hljs-number">6</span>] = appointmentData.<span class="hljs-property">date</span>;
      data[i][<span class="hljs-number">7</span>] = appointmentData.<span class="hljs-property">time</span>;
      data[i][<span class="hljs-number">8</span>] = appointmentData.<span class="hljs-property">message</span>;
      <span class="hljs-comment">// if there's a match  then break the loop</span>
      <span class="hljs-keyword">break</span>;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// if none match than append to new row</span>
      <span class="hljs-keyword">if</span> (i === data.<span class="hljs-property">length</span> - <span class="hljs-number">1</span>) {
        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"Not match"</span>)
        data.<span class="hljs-title function_">push</span>([currentTimeStamp, appointmentData.<span class="hljs-property">name</span>, appointmentData.<span class="hljs-property">email</span>, appointmentData.<span class="hljs-property">address</span>, appointmentData.<span class="hljs-property">company</span>, appointmentData.<span class="hljs-property">purpose</span>, appointmentData.<span class="hljs-property">date</span>, appointmentData.<span class="hljs-property">time</span>, appointmentData.<span class="hljs-property">message</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>,<span class="hljs-string">""</span>])
      }
    }
  }
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
<span class="hljs-comment">// set new values</span>
sheet.<span class="hljs-title function_">getRange</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, data.<span class="hljs-property">length</span>, data[<span class="hljs-number">0</span>].<span class="hljs-property">length</span>).<span class="hljs-title function_">setValues</span>(data);

} <span class="hljs-keyword">catch</span> (e) { <span class="hljs-keyword">return</span> { <span class="hljs-attr">status</span>: <span class="hljs-number">400</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">"Error"</span>, <span class="hljs-attr">data</span>: <span class="hljs-title class_">String</span>(e), } } <span class="hljs-keyword">return</span> { <span class="hljs-attr">status</span>: <span class="hljs-number">200</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">"Appointment Sheets has been successfully updated"</span>, <span class="hljs-attr">data</span>: appointmentData, } }</pre></div><p id="31ae">A few things to notice in the function:</p><ol><li>The object <code>fakeAppointmentData</code> , is very useful, especially for quick testing purposes.</li><li>The function <code>getReadableDate()</code> returns a current date, both date and time, in human-readable format. We'll create it in a moment.</li><li>In this If block,<code> if (data[i][0].slice(0, 10) === currentTimeStamp.slice(0, 10) && data[i][1] === appointmentData.name && data[i][2] === appointmentData.email)</code> , we're making sure that multiple appointment submissions from clients, if they're on the same day, don't get added but updated.</li><li>Inside else block, here: <code>if (i === data.length - 1)</code> , we just want to push the data only once <b>on the last iteration</b>.</li></ol><p id="cfdf">Now let’s create a new file <code>utils.js</code> and write code for <code>getReadableDate().</code></p><div id="a833"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">getReadableDate</span>(<span class="hljs-params">date = <span class="hljs-built_in">Date</span>.now()</span>) { <span class="hljs-keyword">const</span> dt = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(date); <span class="hljs-comment">// padding as two digit, if incase the values returned have 1 digit only</span> <span class="hljs-comment">// for instace, days/month from 1-9, time from 1-9.</span> <span class="hljs-keyword">return</span> <span class="hljs-string"><span class="hljs-subst">${dt.getDate().toString().padStart(<span class="hljs-number">2</span>, <span class="hljs-string">"0"</span>)}</span>/<span class="hljs-subst">${dt.getUTCMonth().toString().padStart(<span class="hljs-number">2</span>, <span class="hljs-string">"0"</span>)}</span>/<span class="hljs-subst">${dt.getFullYear()}</span>,<span class="hljs-subst">${dt.getHours().toString().padStart(<span class="hljs-number">2</span>, <span class="hljs-string">"0"</span>)}</span>:<span class="hljs-subst">${dt.getMinutes().toString().padStart(<span class="hljs-number">2</span>, <span class="hljs-string">"0"</span>)}</span></span> }</pre></div><p id="6769">If you’re coding locally, push changes to the cloud with <code>clasp push</code> .</p><p id="0e88"><i>You may encounter an error because you haven’t pulled in the manifest(appsscript.json) file after that last deployment. Either copy and paste it into your local repo or pull the changes using </i><code>clasp pull</code><i> before pushing.</i></p><p id="5a77">To run the function:</p><ol><li>First, open your sheets file in the GAS editor.</li><li>Select the function in the dropdown in the taskbar and run it.</li></ol><figure id="e193"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*LkVNrSP7n2l3080E.png"><figcaption></figcaption></figure><p id="6e72">You should be able to see the new column with values from the <code>fakeAppointmentData</code> object.</p><p id="f23c">Now, to make it work from the front end we’ll need to redeploy this project and get a new URL. Follow the procedure as we did during test deployment and inside the index.js file, change the <code>BASE_URL</code> value with this new URL.</p><div id="0651"><pre><span class="hljs-keyword">const</span> <span class="hljs-variable constant_">BASE_URL</span> = <span class="hljs-string">"Your Script URL"</span>;</pre></div><p id="461b"><b><i>For Web Apps in Google Apps Script, whenever you make new changes to the script, if that change is needed to be reflected in the front, you’ll have to redeploy the script as the web app again and use the latest script URL as API.’</i></b></p><p id="9ab1">After that, the last change we need to make is to pass the input fields and appropriate <code>reqType</code><b> , updateAppointment, </b>as object parameters into <code>fechData()</code> function inside the <code>handleButtonClick()</code> functions else block.</p><div id="0829"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">handleButtonClick</span>(<span class="hljs-params">e</span>) {

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"handleButtonClick is called"</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name.<span class="hljs-title function_">val</span>());
<span class="hljs-keyword">if</span> (name.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || address.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || email.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || company.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || date.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || time.<span class="hljs-title function_">val</span>().<span class="hljs-property">length</span> &lt;= <span class="hljs-number">0</span> || purpose.<span class="hljs-title function_">val</span>().<span class="hljs-title function_">trim</span>() === <span class="hljs-string">"You need me to"</span> || !termsAndConditions.<span class="hljs-title function_">is</span>(<span class="hljs-string">":checked"</span>)) {
    <span class="hljs-title function_">alert</span>(<span class="hljs-string">"Please fill in all input boxes"</span>);
    e.<span class="hljs-title function_">preventDefault</span>(); <span class="hljs-comment">// don't reload</span>
}

<span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">const</span> appointmentData = {
        <span class="hljs-attr">reqType</span>: <span class="hljs-string">"updateAppointment"</span>,
        <span class="hljs-attr">name</span>: name.<span class="hljs-title function_">val</span>(),
        <span class="hljs-attr">address</span>: address.<span class="hljs-title function_">val</span>(),
        <span class="hljs-attr">email</span>: email.<span class="hljs-title function_">val</span>(),
        <span class="hljs-attr">company</span>: company.<span class="hljs-title function_">val</span>(),
        <span class="hljs-attr">date</span>: date.<span class="hljs-title function_">val</span>(),
        <span class="hljs-attr">time</span>: time.<span class="hljs-title function_">val</span>(),
        <span class="hljs-attr">purpose</span>: purpose.<span class="hljs-title function_">val</span>(),
        <span class="hljs-attr">message</span>: message.<span class="hljs-title function_">val</span>()
    };

    <span class="hljs-title function_">fetchData</span>(appointmentData);
    e.<span class="hljs-title function_">preventDefault</span>();

}</pre></div><p id="5892">Now everything is ready. Re-submit the value from your HTML form, it should work you’ll see a new row in your spreadsheet and your browser’s console should log: <code>{ status: 200, message: "Appointment Sheets has been successfully updated", data: <appointmentData>, }</code></p><h1 id="5561">Summary</h1><p id="83d9">Alright, this concludes part I of the tutorial series. Here we:</p><ol><li>Validated HTML form in simple ways.</li><li>Connected HTML form to the Spreadsheet.</li><li>Learned about API calls using DoGet or DoPost.</li><li>Saved the HTML form submission to the spreadsheet like a SQL database.</li></ol><p id="85d0">In the next part of the series, we’ll use Chat GPT to create 10 questions based on the data submitted by users and save those questions into our spreadsheet. You can find the whole series as a video tutorial from <a href="https://youtube.com/playlist?list=PLP-52qZqWEvkj_riD9IecYtJtYPvDzUFd&amp;si=nXoy2MoGPQZK3VGW">here</a>.</p><p id="34bd">This is <a href="https://nibeshkhadka.com">Nibesh Khadka</a>. Make sure to like and share this post. Consider <a href="https://nibeshkhadka.medium.com/subscribe">subscribing</a> to the email list to get notified regularly about my posts.</p></article></body>

How To Create Web App With Google Apps Script

How to Connect HTML Form To Google Sheets In a Web App?

How To Create Web App With Google Apps Script — Part I

Introduction

In today’s digital age, businesses are increasingly relying on automation to streamline processes and improve efficiency. Google Workspace offers a powerful suite of applications that can be easily integrated to create automated workflows. This tutorial will walk you through the process of creating a web app that integrates Gmail, Sheets, Documents, and Calendar.

In this part, we’ll connect the HTML form with Google Sheets and save the appointment date.

You can find the source code for this project here.

Initial Setup

Initial setup includes creating a working directory and folder structure, creating two folders: Frontend and Backend. Inside the front end, we’ll create two files index.html and index.js. We’ll also be using Bootstrap and JQuery. And implementing JavaScript to validate form fields.

Index.html

<!DOCTYPE html>
<html><head>
  <base target="_top">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
  <div class="container-fluid  px-5">
  </div>
  <div class="row m-4">
    <div class="col-2">
    </div>
    <div class="col-8 col-sm-3">
      <form >
        <div class="mb-3">
          <label for="email" class="form-label">Email address</label>
          <input type="email" class="form-control" id="email" aria-describedby="emailHelp">
          <div id="emailHelp" class="form-text">I'll never share your email with anyone else.</div>
        </div>
        <div class="mb-3">
          <label for="name" class="form-label">Name</label>
          <input type="text" class="form-control" id="name" aria-describedby="nameHelp">
        </div>
        <div class="mb-3">
          <label for="address" class="form-label">Address</label>
          <input type="text" class="form-control" id="address" aria-describedby="addressHelp">
          <div id="addressHelp" class="form-text">Enter your address</div>
        </div>
        <div class="mb-3">
          <label for="company" class="form-label">Company </label>
          <input type="text" class="form-control" id="company" aria-describedby="companyHelp">
          <div id="companyHelp" class="form-text">Enter your Organizations Details</div>
        </div>
        <div class="mb-3">
          <select class="form-select" aria-label="Services">
            <option selected>You need me to</option>
            <option value="Create Add-On">Create Add-On</option>
            <option value="Review Code">Review Code</option>
            <option value="Build Web-App">Build Web-App</option>
            <option value="other">Other</option>
          </select>
        </div>
        <div class="mb-3">
          <label for="date" class="form-label">When?</label>
          <input type="date" class="form-control" id="date" name="date" aria-describedby="dateHelp">
          <div id="dateHelp" class="form-text">Select Date Of Appointment On Weekdays.</div>
        </div>
        <div class="mb-3">
          <label for="time" class="form-label">What Time?</label>
          <input type="time" class="form-control" id="time" name="time" min="09:00" max="17:00" value="10:00"
            aria-describedby="timeHelp">
          <div id="timeHelp" class="form-text">Please select time between 9:00 AM to 5:00 PM</div>
        </div>
        <div class="mb-3">
          <label for="messageArea">Message</label>
          <textarea class="form-control" placeholder="Leave your message here" id="messageArea" name="messageArea"></textarea>
        </div>
        <div class="mb-3 form-check">
          <input type="checkbox" class="form-check-input" id="termsAndConditions" name="termsAndConditions">
          <label class="form-check-label" for="termsAndConditions">I agree with the <a href="https://nibeshkhadka.com"
              target="_blank">terms and conditions </a></label>
        </div>
        <button type="submit" name="submit" id="submit" class="btn btn-primary">Send</button>
      </form>
    </div>
    <div class="col-2">
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
    crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="
    crossorigin="anonymous"></script>
  <script>
   
  </script>
  <script src="./index.js" ></script>
  </div>
</body>
</html>

Index.js

$(document).ready(function () {
    let name = $("#name");
    let email = $("#email");
    let address = $("#address");
    let company = $("#company");
    let date = $("#date");
    let time = $("#time");
    let purpose = $("select");
    let message = $("#messageArea");
    let dateWarningText = $('#dateHelp');
    let timeWarningText = $('#timeHelp');
    let submitButton = $('#submit');
    let termsAndConditions = $('#termsAndConditions');
    // set min date value to today
    let today = new Date().toISOString().split('T')[0];
    document.getElementsByName("date")[0].setAttribute('min', today);// warn user when weekend is selected as appointment date
    $('#date').change(function (e) {
let d = new Date(e.target.value)
        // warn if sunday or saturday
        if (d.getDay() === 0 || d.getDay() === 6) {
            dateWarningText.css('color', 'red');
            $('#date').after(dateWarningText);
        } else {
            // else reset color to default
            dateWarningText.css('color', "")
        }
    })

   // warn user when office hour is not selected as appointment time
    $('#time').change(function (e) {
        console.log(document.getElementsByName("time")[0].value.slice(0, 2));
        if (Number(e.target.value.slice(0, 2)) < 9 || Number(e.target.value.slice(0, 2)) > 17) {
            timeWarningText.css('color', 'red');
        }
        else {
            timeWarningText.css('color', '');
   }
    });

    //  disable button unless agreed to terms and conditions as well as all fields are filled.
    function handleButtonClick(e) {
       if (name.val().length <= 0 || address.val().length <= 0 || email.val().length <= 0 || company.val().length <= 0 || date.val().length <= 0 || time.val().length <= 0 || purpose.val().trim() === "You need me to" || !termsAndConditions.is(":checked")) {
            alert("Please fill in all input boxes");
            e.preventDefault(); // don't reload
        }
        else {
         // for now let's just console log a message
            console.log("All data are valid. They can be submitted to the backend.")
           e.preventDefault();
        }
    }
    submitButton.click(function (e) { handleButtonClick(e); });
});

The form validation will detect empty fields, warn the user of invalid dates or times, and disable submission on empty fields. Also, we’ve made sure that any date before today can’t be selected. Validation is very basic, the project’s main focus is creating an automatic ecosystem using Google Workspace, not front-end development.

Next, we’ll connect the form with the backend. This involves implementing a backend script to handle form submissions, establishing a connection between the front end and the backend, submitting form data to the backend on submission, and storing appointment details in Google Sheets.

Using Google Spreadsheet as a Database

Coding Remotely In VS Code With Clasp

Let’s first go to Google Drive and create a Google Sheets. You can download the one I’m using from the assets folder in the GitHub repo. Then create a bound script from the spreadsheet’s tab.

To pull this project into our local directory we’ll use clasp. If you don’t have the clasp installed then check out my tutorial on using clasp with VS code. We’ll need Project Script ID to link our remote project to this cloud project. It can be found in our Apps Script project from Project Settings>Project ID.

After that in the command line inside of the project directory use this command to clone the project there.

clasp clone "YOUR PROJECT ID" --rootDir .

The period, “.”, is for the current directory if you’re not inside the project folder make sure to provide a proper path instead.

Establishing a Connection between Frontend and Backend

Now, we’ll work on establishing communication between HTML form and Google Spreadsheet. For that let’s make some changes in our index.js file inside the frontend folder.

First, we’ll define BASE_URL which will be the URL address that we’ll use as API to call the backend. Its value is the URL we get after deploying our Apps Script as a Web App later on. We’ll also define the basic payload(options) that’ll be part of the JS fetch method.

const BASE_URL = "";
const PAYLOAD = {
    method: "GET",
    redirect: "follow",
    headers: {
        "Content-Type": "text/plain;charset=UTF-8",
   },
  };

We’ll pass all the values of input fields in the HTML form as a query string. We’ll implement a function called convertPayloadToUrlEncodes() to effectively convert the key-value pairs extracted from the HTML form into a standardized query string format

// convert from {name:Nibesh, address:Helsinki} to name=Nibesh&address=Helsinki
function convertPayloadToUrlEncodes(params = {}) {
    return Object.entries(params)
        .map(([key, value]) => [encodeURIComponent(key), encodeURIComponent(value)].join('='))
        .join('&');
};

Now let’s write code for the function that’ll be making HTTP requests to the spreadsheet.

async function fetchData(params = { reqType: "nothing" }) {
    // modify url    
    const url = `${BASE_URL}?${convertPayloadToUrlEncodes(params)}`;
    
    const res = await fetch(url, PAYLOAD);
    const data = await res.json();
    console.log(data)
}

Apps Script does not support standard request protocols like POST, GET, PUT, or DELETE. Instead, we must utilize a unique identifier, ‘reqType’ in this instance, to determine the appropriate function to execute. This approach will be mirrored in the backend codebase, where a switch case mechanism will handle such requests. For now, it’s crucial to understand that the ‘nothing’ reqType signifies a connection check, not any data manipulation. Additionally, given the lack of front-end actions beyond logging, we will simply record the data returned by the backend.

Next, let’s change the else block of our handleButtonClick() function.

else {
            fetchData()
            e.preventDefault();
        }

We’re not passing any values for now because we only want to check if the connection works. With all this is what our index.js file looks like.

const BASE_URL = "";
const PAYLOAD = {
    method: "GET",
    redirect: "follow",
    headers: {
        "Content-Type": "text/plain;charset=UTF-8",
    },
  };
function convertPayloadToUrlEncodes(params = {}) {
    return Object.entries(params)
        .map(([key, value]) => [encodeURIComponent(key), encodeURIComponent(value)].join('='))
        .join('&');
};
async function fetchData(params = { reqType: "nothing" }) {
    const url = `${BASE_URL}?${convertPayloadToUrlEncodes(params)}`;
  
    const res = await fetch(url, PAYLOAD);
    const data = await res.json();
 
    console.log(data)
}

$(document).ready(function () {
    let name = $("#name");
    let email = $("#email");
    let address = $("#address");
    let company = $("#company");
    let date = $("#date");
    let time = $("#time");
    let purpose = $("select");
    let message = $("#messageArea");
    let dateWarningText = $('#dateHelp');
    let timeWarningText = $('#timeHelp');
    let submitButton = $('#submit');
    let termsAndConditions = $('#termsAndConditions');
    // set min date value to today
    let today = new Date().toISOString().split('T')[0];
    document.getElementsByName("date")[0].setAttribute('min', today);

    $('#date').change(function (e) {
        var d = new Date(e.target.value)
        // warn if sunday or saturday
        if (d.getDay() === 0 || d.getDay() === 6) {
            dateWarningText.css('color', 'red');

            $('#date').after(dateWarningText);
        } else {
            dateWarningText.css('color', "")
        }
    })

    // time
    $('#time').change(function (e) {
        console.log(document.getElementsByName("time")[0].value.slice(0, 2));
        if (Number(e.target.value.slice(0, 2)) < 9 || Number(e.target.value.slice(0, 2)) > 17) {
            timeWarningText.css('color', 'red');
        }
        else {
            timeWarningText.css('color', '');
        }
    });

    //  disable button unless agreed to terms and conditions as well as all fields are filled.
    function handleButtonClick(e) {
        console.log("handleButtonClick is called");
        console.log(name.val());
        if (name.val().length <= 0 || address.val().length <= 0 || email.val().length <= 0 || company.val().length <= 0 || date.val().length <= 0 || time.val().length <= 0 || purpose.val().trim() === "You need me to" || !termsAndConditions.is(":checked")) {
            alert("Please fill in all input boxes");
            e.preventDefault(); // don't reload
        }
        else {
           
            fetchData()
            e.preventDefault();
        }
    }
    submitButton.click(function (e) { handleButtonClick(e); });
});

Web App and DoGet() or DoPost()

Before we write server-side code. Let’s briefly understand how exactly does connection is established as a Web App in an app script project. Apps Script provides two methods for this DoGet and DoPost. We can use either of them. These two are the method that receives the requests from the front end.

Both of these functions provide access to a JS object, “e” as mentioned in the documentation. This parameter provides access to the query strings that we’ll pass in fetchData() as part of the URL, returned by the convertPayloadToUrlEncodes() function. Each parameter can be accessed from the parameter JS object inside the e parameter. For instance: The values in the https://script.google.com/.../exec?username=jsmith&age=21 URL can be accessed as e.parameter.name and e.parameter.age.

Create an API with Apps Script

Now let’s get back to our project. We’ll create a new file “api.js” inside of our backend folder in VS code.

function doGet(e) {
    try {
        var reqType = e.parameter.reqType;
        var param = e.parameter;

        switch (reqType) {
                
                    default:
                        return contentService({
                            status: 200,
                            message: "Connection Successfull",
                            data: "",
                        });
                }
      } catch (err) {
            contentService({
                status: 400,
                message: "Error",
                data: err,
            });
        }
    }


function contentService(data) {
    return ContentService.createTextOutput(JSON.stringify(data)).setMimeType(
        ContentService.MimeType.JSON
    );
}

As I’ve already mentioned we’ll be using the query string reqType as the keyword to switch the API request. Since now we’re just establishing a connection we’ll only define the default switch case and return a connection successful message. We’ll also define error just in case.

ContentService in Apps Script can be used to return the output as JSON like I’m doing here.

If you’re using the DoPost() instead of the DoGet() method, make sure to change the method from “GET” to “Post” in index.js’s Payload, or else you can’t establish a connection.

Now, we’ll have to push changes from VS code to the cloud. Before that, I’ll create another file, .claspignore, in our root directory and frontend folder’s path there, because I don’t need a frontend folder in my apps script project.

**/frontend/**

Now push the backend folder to the cloud with the command clasp push .

Deploying the App Script Project and Acquiring URL

Remember our BASE_URL is still empty. Before pushing changes to the cloud project, we must deploy the web app to make it accessible online. This deployment process generates a unique URL as the entry point for accessing the web app. We'll need to capture this URL to establish a proper connection from the front. Let's deploy our script as a Web App.

  1. Go to the apps script project in the cloud and click on the deploy button in the top right corner.
  2. On the popup window:
  3. Select Web App
  4. Select “Anyone” for Who has access? dropdown
  5. Deploy the project
  6. Copy the script URL and paste it as the value for BASE_URL.

After saving everything load the HTML file in the browser fill in every input field and submit the data. The console of the browser should have logged the connection established message.

Centralized Storage for Project IDs and API Keys

Before we start coding to save the data to the spreadsheet let’s first create a configuration file, named cofig.js. It’ll be a file where we’ll save our ID for various files and folders, from Google Drive that are part of this project. We’ll also save the API key of ChatGPT here.

var GPT_SECRET_KEY = ""; // gpt secert key
var FORM_FOLDER_ID = "";// folder to store forms created from questions
var DOCS_FOLDER_ID = "";// folders to store docs ceated from user's response to the forms
var TEMPLATE_ID = "";// ID for the template used to create Docs
var APPOINTMENT_CALENDAR_ID = ""; // id for Google Calendar used to notify for calendar
var MARK_REVIEWED_IMAGE_LINK_ID = ""; // id for the image that'll be embedded into the docs
var SCRIPT_URL = ""; // URL returend after deploying the script as web app.

Read comments for the purpose creation of each variable.

Create Folders and Files that are necessary for this project into your Google Drive. Mine looks like the image given below. You can download images and templates from the assets folder in the GitHub repo.

You can get Folder’s and Doc’s ID from its URL after opening it as shown in the image below.

To get IDs from files like PDF, images, etc, First, get the shareable link and then copy the highlighted section as shown in the image below.

To get or create the Secret Key for the Chat GPT, go to your profile on OpenAi.com and follow the instructions in the image below.

For URL leave it empty cause we don’t need it now.

Make sure to save all those values and push the changes to the cloud with a clasp.

Utilizing the var keyword for variable declaration instead of let or const ensures global accessibility from other files within the project.

Additionally, you’ll find the config_4_tutorial.js file instead of the config.js file in the GitHub repo, ensuring its confidentiality.

Saving HTML Form Into Google Sheets

Now, let’s save the data to the spreadsheet. For that make the following changes inside the switch method of the api.js file.

//...... continue  
switch (reqType) {
            case "updateAppointment":
                const newAppointmentData = { ...fakeAppointmentData };
                newAppointmentData.name = param.name;
                newAppointmentData.email = param.email;
                newAppointmentData.address = param.address;
                newAppointmentData.company = param.company;
                newAppointmentData.purpose = param.purpose;
                newAppointmentData.date = param.date;
                newAppointmentData.time = param.time;
                newAppointmentData.message = param.message;
          
          return contentService(updateAppointmentDataInSheets(newAppointmentData));
// continue ...

We’re using the reqType updateAppointment as keyword here. We'll have to pass this same keyword in our index.js file later on. If the condition is satisfied we call the function updateAppointmentDataInSheets() and pass the values as JS object. We'll create this function and fakeAppointmentData JS object inside a new file sheet.js in the backend folder.

var ss = SpreadsheetApp.getActiveSpreadsheet();
// all data except the timestamp
var fakeAppointmentData = {
  email: "[email protected]",
  name: "Arttu Karjalainen",
  address: "Helsinki",
  company: "Himali Coders",
  date: "2023-10-19",
  time: "10:00",
  message: "An issue with the script needs fixing. It was working fine, but then I changed ownership of some google folders  (since I'm using the later for work typically so it's more convenient to have everything owned by that account). Now we're seeing attached error 'access denied driveapp' on execute population.",
  purpose: "Review Code",
}

function updateAppointmentDataInSheets(appointmentData = fakeAppointmentData) {
  try {
    const sheet = ss.getSheetByName("Appointments");
    const data = sheet.getDataRange().getValues();
    const currentTimeStamp = getReadableDate();
   
    if (data.length === 1) {
      data.push([currentTimeStamp, appointmentData.name, appointmentData.email, appointmentData.address, appointmentData.company, appointmentData.purpose, appointmentData.date, appointmentData.time, appointmentData.message,"","","","","",""])
    } else {
      for (let i = 1; i < data.length; i++) {
        // if name, email and time-stamp 
        if (data[i][0].slice(0, 10) === currentTimeStamp.slice(0, 10) && data[i][1] === appointmentData.name && data[i][2] === appointmentData.email) {
          data[i][0] = currentTimeStamp;
          data[i][3] = appointmentData.address;
          data[i][4] = appointmentData.company;
          data[i][5] = appointmentData.purpose;
          data[i][6] = appointmentData.date;
          data[i][7] = appointmentData.time;
          data[i][8] = appointmentData.message;
          // if there's a match  then break the loop
          break;
        } else {
          // if none match than append to new row
          if (i === data.length - 1) {
            console.log("Not match")
            data.push([currentTimeStamp, appointmentData.name, appointmentData.email, appointmentData.address, appointmentData.company, appointmentData.purpose, appointmentData.date, appointmentData.time, appointmentData.message,"","","","","",""])
          }
        }
      }
    }
    console.log(data);
    // set new values
    sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
  }
  catch (e) {
    return {
      status: 400,
      message: "Error",
      data: String(e),
    }
  }
  return {
    status: 200,
    message: "Appointment Sheets has been successfully updated",
    data: appointmentData,
  }
}

A few things to notice in the function:

  1. The object fakeAppointmentData , is very useful, especially for quick testing purposes.
  2. The function getReadableDate() returns a current date, both date and time, in human-readable format. We'll create it in a moment.
  3. In this If block, if (data[i][0].slice(0, 10) === currentTimeStamp.slice(0, 10) && data[i][1] === appointmentData.name && data[i][2] === appointmentData.email) , we're making sure that multiple appointment submissions from clients, if they're on the same day, don't get added but updated.
  4. Inside else block, here: if (i === data.length - 1) , we just want to push the data only once on the last iteration.

Now let’s create a new file utils.js and write code for getReadableDate().

function getReadableDate(date = Date.now()) {
  const dt = new Date(date);
  // padding as two digit, if incase the values returned have 1 digit only
  // for instace, days/month from 1-9, time from 1-9.
  return `${dt.getDate().toString().padStart(2, "0")}/${dt.getUTCMonth().toString().padStart(2, "0")}/${dt.getFullYear()},${dt.getHours().toString().padStart(2, "0")}:${dt.getMinutes().toString().padStart(2, "0")}`
}

If you’re coding locally, push changes to the cloud with clasp push .

You may encounter an error because you haven’t pulled in the manifest(appsscript.json) file after that last deployment. Either copy and paste it into your local repo or pull the changes using clasp pull before pushing.

To run the function:

  1. First, open your sheets file in the GAS editor.
  2. Select the function in the dropdown in the taskbar and run it.

You should be able to see the new column with values from the fakeAppointmentData object.

Now, to make it work from the front end we’ll need to redeploy this project and get a new URL. Follow the procedure as we did during test deployment and inside the index.js file, change the BASE_URL value with this new URL.

const BASE_URL = "Your Script URL";

For Web Apps in Google Apps Script, whenever you make new changes to the script, if that change is needed to be reflected in the front, you’ll have to redeploy the script as the web app again and use the latest script URL as API.’

After that, the last change we need to make is to pass the input fields and appropriate reqType , updateAppointment, as object parameters into fechData() function inside the handleButtonClick() functions else block.

function handleButtonClick(e) {

    console.log("handleButtonClick is called");
    console.log(name.val());
    if (name.val().length <= 0 || address.val().length <= 0 || email.val().length <= 0 || company.val().length <= 0 || date.val().length <= 0 || time.val().length <= 0 || purpose.val().trim() === "You need me to" || !termsAndConditions.is(":checked")) {
        alert("Please fill in all input boxes");
        e.preventDefault(); // don't reload
    }

    else {
        const appointmentData = {
            reqType: "updateAppointment",
            name: name.val(),
            address: address.val(),
            email: email.val(),
            company: company.val(),
            date: date.val(),
            time: time.val(),
            purpose: purpose.val(),
            message: message.val()
        };

        fetchData(appointmentData);
        e.preventDefault();
}

Now everything is ready. Re-submit the value from your HTML form, it should work you’ll see a new row in your spreadsheet and your browser’s console should log: { status: 200, message: "Appointment Sheets has been successfully updated", data: <appointmentData>, }

Summary

Alright, this concludes part I of the tutorial series. Here we:

  1. Validated HTML form in simple ways.
  2. Connected HTML form to the Spreadsheet.
  3. Learned about API calls using DoGet or DoPost.
  4. Saved the HTML form submission to the spreadsheet like a SQL database.

In the next part of the series, we’ll use Chat GPT to create 10 questions based on the data submitted by users and save those questions into our spreadsheet. You can find the whole series as a video tutorial from here.

This is Nibesh Khadka. Make sure to like and share this post. Consider subscribing to the email list to get notified regularly about my posts.

Google Apps Script
Google Sheets
ChatGPT
Google Calendar
JavaScript
Recommended from ReadMedium