10

I want to call a function I wrote within my Google Apps Script. When I execute a getJSON I suppose it'll automatically run my doGet(e).

My Javascript:

$.getJSON(https://script.google.com/macros/s/[ID]/exec, function(data){ 
   //code here
});

Is there a possible way to call one of my custom functions for example

My Google Apps Script:

function getNumberOfFans(e){ 
   //code here
}

Do I have to add some kind of extra function parameter to my URL?

Rubén
  • 34,714
  • 9
  • 70
  • 166
Rover
  • 387
  • 4
  • 14

1 Answers1

32
  • In either a "stand alone" or bound Apps Script file add a doGet(e) function.
  • Publish the Apps Script file as a Web App.
  • Get the published URL of the Web App.
  • Add a search string parameter to the end of the URL.

You can add search string parameters to the URL of the published Wep App.

Here is an example:

https://script.google.com/macros/s/[ID]/exec?searchStringName=functionOne

The search string is at the end of the URL, after exec. You must add a question mark after exec and then name=value

url/exec?name=value

Where name and value will be replaced with your choices.

Put the event argument (denoted by the letter "e") into the doGet(e) function, not the function you want used.

function doGet(e) {
  var passedString,whatToReturn;

  passedString = e.parameter.searchStringName;
  if (passedString === 'functionOne') {
    whatToReturn = functionOne();  //Run function One
  };

  return ContentService.createTextOutput(whatToReturn);
};

function functionOne() {
  var something;

  //. . . . Code;
  something = code here;
  return something;
};

The above code is for a GET request. If you want to use a POST request, don't use a search string in the URL. For a POST request, you will send information in the payload. You'll still use e.parameter to access the data sent, but whatever is in e.parameter will be an object with key/value pairs. You'll need to know what the key (property) name is that was sent in the object.

For an explanation on URL Parameters, see this documentation:

URL Parameters

Alan Wells
  • 30,746
  • 15
  • 104
  • 152
  • 2
    Nice one - I'm favoriting it! – Mogsdad May 08 '15 at 19:33
  • I got always error message: 401_client_error for a POST call, and cannot find a case online to show how that doPost works. Any idea? thanks. – Albert Jun 20 '18 at 12:42
  • You may need to post a question with the details of how you make the POST request, and the `doPost(e)` function that you are using. – Alan Wells Jun 20 '18 at 16:26
  • @Albert: maybe it's because you were testing with a Rest client like Postman? It doesn't work with Postman in my case also. But when I tried using a normal
    , it worked as expected
    – 0xh8h Jul 30 '19 at 02:25