Search code examples
google-apps-scriptgoogle-sites

How to pass values from ScriptDb to Google Sites gadget


I have a Google Sites page with an embedded Apps Script gadget. On the page, I want to display ScriptDb data upon clicking a button.

My question is: how can I pass ScriptDb results to the JavaScript embedded in my gadget?

Here is my source:

[Sample-Code.gs]

function doGet() {
  // return template page
  return HtmlService
      .createTemplateFromFile('Sample-HTML')
      .evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE);
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}

// assume db contains 10 'records'
function getData(query) {
  var db = ScriptDb.getMyDb(); 
  var data = db.query(query);
  Logger.log(data.getSize()); // returns '10.0'
  return data; // makes showData think this is null
}

[Sample-HTML.html]

<?!= include('Sample-JavaScript'); ?>

<input type="button" value="show data"
    onclick="google.script.run
    .withSuccessHandler(showData)
    .getData({})" />

[Sample-JavaScript.html]

<script>
function showData(db_query_result) {
alert(db_query_result); // returns null.
}
</script>

Solution

  • The value returned by db.query() is an object as defined in the documentation that can not be used directly in your UI, you should return the value in a format that can be shown in the page : a string or an array of strings.

    I didn't test but this should work :

    function getData(query) {
      var db = ScriptDb.getMyDb(); 
      var result = db.query(query);
      Logger.log(result.getSize()); // returns '10.0'
      var results = db.query({type: 'person'});
      var data = [];
      while (results.hasNext()) {
       data.push(results.next());
      }
      return data; // data is an array of results
    }