user2348688
user2348688

Reputation: 153

How to get Spreadsheet Data into clientside array via HTMLService (Google App Scripts)

I am using GAS HTMLService to design a Web App and have hit a major hurdle that I can't seem to overcome -- so I'm hoping to get some help from y'all.

I'm able to create the template and display the HTML properly using the standard doGet:

function doGet(e){
var ss = SpreadsheetApp.openById('SpreadSheetKey');
var usersheet = ss.getSheetByName('UserInfo');
var lastRow = usersheet.getLastRow();
var Userrange = usersheet.getRange(2, 1, lastRow-1, 4);
var Uservalues = Userrange.getValues();
var length = Uservalues.length;

var template = HtmlService.createTemplateFromFile('Form.html');
template.stuff = {};
template.stuff = Uservalues;

template.action = ScriptApp.getService().getUrl();

return template.evaluate();
}

The HTML will render up fine so long as I remove this piece of code from my HTML file:

  $('#chkP').click(function(){
var email = '<?=email?>';
var usename = $('#myuserName').val();

for(var i=0;i<num;i++){
var name = '<?!=stuff[i][0]?>';
alert(name);
}    
});

The issue appears to be related to trying to use the 'i' variable -- I can get the proper info using:

'<?=stuff[2][0]?>' // THIS WORKS

<?=stuff[i][0]?> //THIS DOES NOT -- IT IS ALWAYS undefined 
// it's like 'i' and <?stuff?> aren't in the same scope??

so I have the theory that I have a ServerSide array:

 (Spreadsheetapp.blahblah.getValues();) 

that is not available for the Client Side to play with.

My question to you folks is how do I get this data from the Spreadsheet into the HTML form and available to iterate through as an array using a simple 'for' loop....

OR is there a better way?

Upvotes: 2

Views: 1591

Answers (1)

Corey G
Corey G

Reputation: 7858

You are correct that the array is on the server. Any code inside <? .. ?> is server code) and not available on the client.

What you can do is copy the entire array to the client, so that you can iterate through it later:

Suppose you had an array on the server:

<? var serverStuff = [1, 2, 3]; ?>

You can tell the template to copy it over to the client (basically, write the values of it directly into the client code.

<script>
    ...
    var clientStuff = <?!= JSON.stringify(serverStuff) ?>;
    ...

    // Now you have it on the client! You can use it here:
    alert(clientStuff[0]);
</script>

You can see what is happening by logging the content of the template (after evaluating) on the server:

Logger.log(template.evaluate().getContent());

Which would give you this actual client code, with the copy of the array written into it:

<script>
    ...
    var clientStuff = [1, 2, 3];
    ...

    // Now you have it on the client! You can use it here:
    alert(clientStuff[0]);
</script>

Upvotes: 5

Related Questions