Search code examples
google-apps-scriptgoogle-apps

GAS - take value from jquery and pass it over to a var in the code.gs


I am trying to take the email value from the jquery and pass it over to a var in the code.gs. The code that I currently have is:

code.gs:

function getUser(){
  user = Session.getActiveUser().getEmail();
  return user;
}
 function getUsername(){

  Logger.log(emailSource);
  Console.log(emailSource);
}

Jquery:

    var user;
google.script.run.withSuccessHandler(getUserEmail).getUser();
function getUserEmail(userMail){
  user = userMail;
  $("#username").ready(function(){
   $("#username").text(userMail);
    });
}
    function getUserEmail2code(emailSource){
   var emailSource = $('#username').text();
   $('#username').append(emailSource);
   google.script.run.withSuccessHandler(getUserEmail2code).getUsername();
    });

My Idea is to grab that email address to be able to manipulate with the google sheets and assign specific rules to each.

Many thanks


Solution

  • to pass values from Client JavaScript to server code you have to use a very similar workflow, below is a shematic example with comments:

    (be careful to check the \' used near the onclick to add the parameters)

      ...
      var someValue = $('#someDIV').val(); // get a value using JQuery and insert it in the onclick
      ...
      $('#someOtherDiv').append('<br><input type="button" id="someID" onclick="someFunctiont(\''+someValue+'\')" value="this will call the function with parameter">');
      ...
    
      function someFunction(parameter){
        //call a server function here  using Google.script.run
        google.script.run.withSuccessHandler(otherClientFunctionToEventuallyDoSomething).serverFunction(parameter);
        ...
    
    
    // in server .gs code :
      function serverFunction(parameter){
        // do something with the parameters...
      }