Search code examples
javascriptgoogle-apps-scriptgoogle-app-maker

Is it possible to pass a variable from a client script to a server script?


Using Google App Maker, I'm trying to run a Client Script to get a variable, and then pass that variable to a Server Script so that it can use the same one. I can't seem to work it out.

My Client Script looks in a table called OrderItems and returns the ProductNumber of the current record.

The Client Script then calls the Server Script which should use the ProductNumber that the Client Script returned to run a query on another table.

CLIENT SCRIPT

var productNumberToUpdate = app.datasources.Purchase_Order_Line_Items.item.Stocked_Item_Product_Number.toString();
google.script.run.serverScript();

SERVER SCRIPT

var query = app.models.Inventory_Item.newQuery();
query.filters.Part_Number._startsWith = productNumberToUpdate;
var results = query.run();
var id = results[0]._key;

The Client Script runs successfully but the Server Script returns the error ReferenceError: productNumberToUpdate is not defined. This is unsurprising given that the variable productNumberToUpdate is indeed not defined, which is why I want to pass it from the Client Script.


Solution

  • You can pass variables by using parameters in your function.

    Client script

    var productNumberToUpdate = app.datasources.Purchase_Order_Line_Items.item.Stocked_Item_Product_Number.toString();
    google.script.run.serverScript(productNumberToUpdate);
    

    Server script

    function serverScript(productNumberToUpdate) {
      var query = app.models.Inventory_Item.newQuery();
      query.filters.Part_Number._startsWith = productNumberToUpdate;
      var results = query.run();
      var id = results[0]._key;
    }