Gee57
Gee57

Reputation: 11

Google apps script, pass (two) 2 "variables" or "array" from code.gs to index.html / Javascript

I need to pas 2 “variables” or “arrays” from my Code.gs to my index.html / javascript. The 2 “variables” are the values of my sheet and the background color of the cells. If I only pass 1 variable (waardes or kleuren) the function works, if I try to pass them both, I only get the last variable passes in the “return waardes , kleuren”.

// code.gs

function getSheetData(){
    var ss = spreadsheetApp.openById("1EpOCr_wjeYhn2YsQjRpAaUtaJNKv_4Rf81vnG59EvPA").getSheetByName("sheet");
    var waardes, kleuren;
    waardes = ss.getDataRange().getValues();
    kleuren = ss.getDataRange().getBackgrounds();

    return waardes, kleuren; 
}

// index.html / javascript

function functionShowSheet() {
    google.script.run.withSuccessHandler(showValuesandColors).getSheetData();

    function showValuesandColors (waardes, kleuren) {
        alert(waardes);
        alert(waardes[0][0]);
        // do something with the  values and colors
    }
}

Upvotes: 1

Views: 6733

Answers (1)

m5khan
m5khan

Reputation: 2717

As with the basic programming concept, most programming languages return only one value from the function. Read this article "Why do most programming languages only return a single value from a function?"

So you cannot return multiple values in multiple variables from a function in javascript.

What to do then?

You can return a collection i.e an object or an array containing multiple values from a function.

function getSheetData(){
    var ss = spreadsheetApp.openById("1EpOCr_wjeYhn2YsQjRpAaUtaJNKv_4Rf81vnG59EvPA").getSheetByName("sheet");
    var waardes, kleuren;
    waardes = ss.getDataRange().getValues();
    kleuren = ss.getDataRange().getBackgrounds();

   return {waardes: waardes, kleuren: kleuren}; 
}

And then get the values in index.html

function showSheet(){
    google.script.run.withSuccessHandler(showValuesandColors).getSheetData();
}

function showValuesandColors (myObj) {
    var waardes = myObj.waardes;
    var kleuren = myObj.kleuren;
}

You can also return an array instead of an object like this:

in code.gs

function getSheetData(){
    ....
    var resArr = [waardes, kleuren];
    return resArr;
}

in index.html

function showValuesandColors (myArr) {
    var waardes = myArr[0];
    var kleuren = myArr[1];
}

Upvotes: 2

Related Questions