Bipin Sasi Techie, Author of the book Leadership Puzzles You can follow me on X formerly called twitter @BipinSasi No comments

Apps Script : The Concept of the Callback







Handling User Actions


In order to work, a button needs an event handler. However, buttons are not the only
elements that can have handlers, and click is not the only handler type. For example,
a text box may have a handler that responds to the user pressing the Enter key, or a
listbox sometimes needs to fill a second list for situations like choosing a city after the
state has been selected. In such a case, we might use an onChange handler. In more
advanced UIs, mouse handlers like over and off can create rich user interaction by
displaying information before a selection is made. It’s also important to note that an
element can have more than one handler. When you have a process that may take some
time, like receiving data from a web service or uploading files from the hard drive, it’s
a good idea to show a progress indicator to the user after he has clicked, and an additional
handler may take care of that detail.
In this chapter, we will keep things simple and only work with the submit handler to
provide action for our simple form.


Anatomy of a Handler
Google Apps Script allows us to use jQuery, which is the preferred technique in HTML
programing to date. I highly recommend learning as much jQuery as possible. In the
long run, it will save you countless hours of trying to figure out how to write something
in pure JavaScript—because that thing has already been included in jQuery and can be
accomplished by simply pasting in a single command.
Let’s start where we left off in Chapter 3 by opening our existing Contact Me code. The
first thing we need to do is import the jQuery library into our index.html file. You can
import the jQuery library in a number of different ways, such as by saving a copy on
your server or in Google Drive. There are quite a few publicly available custom versions,
but because Google Apps Script uses Caja and can be very picky about any imported
code, I recommend using a particular version provided by Google.

To import this version of jQuery, add the following line of code to the end of your
index.html file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Now that we have installed jQuery, let’s add an event to the “submit” button. We want
the page to always display as quickly as possible, and we want to avoid any issues with
a browser that might try to load things in a strange order. When we want to add an event
to any object on the page, that object must be there to attach to, or the process will fail.
The safest way to accomplish this is to use the jQuery ready method, which will watch
for the page to be fully loaded before it starts executing JavaScript.
The ready method looks like this:
$( document ).ready(function() {
console.log( "ready!" );
});
To attach our event handler to the button, we will use the submit method because it will
detect a mouse click or Enter keypress. Again, this is one of those examples where jQuery
saves us a line of code to take care of a simple task.
Add the following code to the end of your index.html file:
<script>
$( document ).ready(function() {
$( "#email_subscribe" ).submit(function() {
$( "#thank_you" ).show();
});
});
</script>

Now let’s break that down. After the page is loaded and ready, we use the jQuery $ to
get the Document Object Model (DOM), which you can think of as all the code on the
page, to get the form element by its ID. If you look in the HTML section of the index.
html code, we used <form id="email_subscribe"> to identify the form itself. Now
we can call on it by name:
$( "#email_subscribe" )







Next we attach the submit method to the form. This method takes a function to perform
tasks, and we will be unhiding the “Thank you” message by again using jQuery to get
the #thank_you span element and asking jQuery to show it.
Save your work and give it a test by loading the “latest code” dev link. You now have a
working “submit” button, and we are performing actions on the page. In the next section
we will start working with server-side callbacks in order to process the data to a spreadsheet.
Here is the full code for index.html so far:
<div>
<form id="email_subscribe">
<input type="email" name="email" id="email" placeholder="Enter your email">
<input type="submit" value="Subscribe">
</form>
<span id="thank_you" hidden="true">Thank you!</span>
</div>
<?!= HtmlService.createHtmlOutputFromFile('CSS').getContent(); ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {
$( "#email_subscribe" ).submit(function() {
$( "#thank_you" ).show();
});
});
</script>





The Concept of the Callback

When your app needs to do something—like update information on the screen, add
data to a spreadsheet, or send an email—it performs what is known as a remote procedure
call, or RPC for short. An RPC includes sending code to the server for processing,
referred to as a call, and having the server send back the results, known as a callback. I
am sure that Java developers are pulling their hair out at this simplistic definition of
RPCs, but for what you need to know in Google Apps Script, this about covers it.

In our case, we will want to get the input from the text box and write it to a spreadsheet.
This means we need to construct a call from our index.html file and pass our text box
value to a function in the Code.gs file, which we can consider as our server. To make it
a little easier to understand, let’s get the server-side part started, so there is something
to refer to when making the call.
Open up the Code.gs file and add this function:
function addEmail(form){
Logger.log(form.email);
return 200;
}
This is a simple function that will let us know that we are indeed getting a response from
the server. Remember that you will only be able to check the log if you run the app, but
for our case we are going to return the value 200, which is the web standard for a
successful execution.


Now, back in the index.html file, it’s time to make the call by modifying the submit
function. Google Apps Script has a few special ways to run an RPC, but the one we will
use most of the time looks like this:
google.script.run.withSuccessHandler(serverResponseFunction).serverFunction-
Name();
What we are doing is calling a server function in one of our .gs files; if it does not send
back an error, we run a function here on the client side to process whatever the server
returned.

Replace $( "#thank_you" ).show(); within the submit method function with the
following code:
google.script.run.withSuccessHandler(function(ret){
console.log(ret);


Here we are asking to run a function called addEmail on the server, which we will pass
the whole form: i.e., this. If you look back at the submit handler, you’ll see that we
attached it to the form so that when the button is clicked this represents the form. If
the server call is successful, when we get the callback we will run the function within
the withSuccessHandler arguments. Because we expect a return value, we add the argument
ret to represent what’s returned. It can be just about any JavaScript element.
Just to check out the functionality, we will give a little output to the JavaScript Console.
Be sure you know how to open the JavaScript Console on your browser, because we use
it a bunch when building frontends.

Believe it or not, the frontend and user actions are almost done. All we need now is to
hide the form and display the “Thank you” with a little style. Just above the con
sole.log line, add:
$( "#thank_you" ).show("slow");
$("#email_subscribe").slideUp();
Now give it a whirl, and you have finished the user experience side of this application


That was a lot to cover, so here is what the entire code for index.html looks like:
<div>
<form id="email_subscribe">
<input type="email" name="email" id="email" placeholder="Enter your email"></form>
<span id="thank_you" hidden="true">Thank you!</span>
</div>
<?!= HtmlService.createHtmlOutputFromFile('CSS').getContent(); ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {
$( "#email_subscribe" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
$( "#thank_you" ).show("slow");
$("#email_subscribe").slideUp();
console.log(ret);
}).addEmail(this); //"this" is the form element
});
});
</script>



Functions Are Where the Action Happens
Applications built on the server side in Google Apps Script have four basic types of
functions: doGet, which you are familiar with; doPost, which you will learn about later;
functions that return values directly; and functions that are intended to be used via a
trigger. They aren’t really that different; however, when you use them can be important.
For example, you always need doGet to display the UI in a gadget or web app, and if you
are using a form from a different service, you will likely need a doPost function.
When you operate a function using an event handler and your intent is to send some
information to the server, you must use google.script.run.


Storing the Values
I have saved the best for last—or maybe the easiest part, depending on how you look at
it. The app you have been building has all the features needed to interact with the user,
but we are lacking the most important thing: a place to store the data and a way to get
it there. Not to worry: Google has provided us with several data-storage options that
should work for most applications. One great option is a spreadsheet, and this is typically
where you would store data like this. Next, there is ScriptDB, which we will get to later
in the book. Another option for very important or very large sets of data is Cloud SQL.
This is an excellent service and requires payment, but the cost is small given all the
features.

What is Google App Engine?

Sal Bipin Sasi
6 min read

Comments (0)

Post a Comment

Cancel