Home > Software engineering >  In JS how to pass Array Parameter to GAS and then retrieve result
In JS how to pass Array Parameter to GAS and then retrieve result

Time:05-26

In my Google Sheet I have a list of books with their details. The user inserts the title he's looking for, jQuery passes the title to a function in GAS and then it returns the matches (found books) to the JS.

Here my code.

HTML

<form id="formD">
  <input type="text" id="title" name="title" placeholder="Math">
  <button id="submit">Search</button>
</form>

JS

$("#submit").click(function()
{
  var data = [];
  data.push($("#title").val()); //title the user is looking for
  google.script.run.withSuccessHandler(onSuccess).find(data);
});

function onSuccess(a)
{
    alert(a); //example
}

GAS

function doGet() {
  return HtmlService.createTemplateFromFile('index')
    .evaluate()
    .addMetaTag('viewport', 'width=device-width, initial-scale=1');
}

function find(data) {
  var sheet = SpreadsheetApp.openById("XXX").getSheetByName("XXX");
  var range = sheet.getRange("A:G");
  var values = range.getValues();

  var result = [];

  var title = data[0];

  for(i=0; i < values.length; i  ){
    if(values[i][0] != "")
    {  
       if(values[i][2].includes(title))
         result.push(values[i]);
    }
  }

  return result
}

I don't know how to parse and use the array I pass to GAS. When the button "search" is clicked, the page is reloaded and the value appended to the URL.

CodePudding user response:

Try it this way

function find(data) {
  var sheet = SpreadsheetApp.openById("XXX").getSheetByName("XXX");
  var range = sheet.getRange("A1:G"   sheet.getLastRow());
  var values = range.getValues();
  var result = [];
  var title = data;
  for (let i = 0; i < values.length; i  ) {
    if (values[i][0] != "") {
      if (values[i][2].includes(title))
        result.push(values[i]);
    }
  }
  return result;
}

function onSuccess(a) {
    alert(a.join('\n')); //example
}

js:

No need for data to be an array

$("#submit").click(function() {
  var data = $("#title").val(); 
  google.script.run.withSuccessHandler(onSuccess).find(data);
});

client to server communications

CodePudding user response:

Here is the solution to the problem that when clicking the button the page reloads.

$("#sumbit").click(function(){

}

This piece of code was outside $(document).ready(function(){}).

  • Related