Maths89
Maths89

Reputation: 486

How to get data from Google Spreadsheet to HTML as a javascript variable?

I am trying to create webapp with html service. Here is my code.

The code in code.gs file.

function doGet() {
  return HtmlService
      .createTemplateFromFile('userendhtml')
      .evaluate();
}

function getData() {
var sss = SpreadsheetApp.openById('xxxx'); 
var rawData =  sss.getDataRange().getValues()     
var data = []                       
for (var i = 0; i< rawData.length; i++){

data.push(rawData[i])

}
  return data
}

Now I want to access this data as javascript variable for further processing (for creating table with querying). The code in userendhtml.html is

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
<script>
 var data2 = getData();
</script>
  </body>
</html>

This doesn't store data to variable data2. So how to get data from spreadsheet in variable in javascript?

Upvotes: 0

Views: 1580

Answers (2)

Cooper
Cooper

Reputation: 64110

You could use the techniques found in the Templated Html reference that I gave you. But you could also do this:

<script>
  var data2;
window.onload=function(){
  google.script.run
  .withSuccessHandler(function(dt){
    data2=dt;
    document.getElementById('myDiv').innerHTML=data2;
  .getData();
}
</script>

The templated html approach loads on the server and this approach loads after the dom loads.

I just tested this example as a dialog

    function dialogTest() {
      var html='<div id="mydiv"></div>';
      html+='<script>var data2;window.onload=function(){google.script.run.withSuccessHandler(function(dt){data2=dt;document.getElementById("mydiv").innerHTML=data2;}).getMtData();}</script>';
      SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Dialog Test');
    }

    function getMtData() {
      return 'Hello World';
    }

Upvotes: 1

IMTheNachoMan
IMTheNachoMan

Reputation: 5839

You want to use google.script.run in conjunction with withSuccessHandler(...)

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <script>
      var data2;

      google.script.run.withSuccessHandler(function(ret){
        data2 = ret;
      }).getData();
    </script>
  </body>
</html>

Upvotes: 2

Related Questions