0

I have created a Google Form that successfully enters user responses into a Google Sheet. I tried to create a function that would read the submitted responses when triggered by a form submit, but I can not get it to work. Here is the beginning of the function I created by following various online examples:

function onFormSubmit(e) {

  //get the form responses
  var formResponse = e.response;

  //get an array with all the response values (values in the array are ordered as on the form)
  var itemResponses = formResponse.getItemResponses();

  //get the responses (array items start from 0)
  var FirstName = itemResponses[0].getResponse();
  var LastName = itemResponses[1].getResponse();

Here is the error message I get when it runs, which indicates the problem is with the "formResponse.getItemResponses()" statement:

TypeError: Cannot read properties of undefined (reading 'getItemResponses') at onFormSubmit(Code:7:36)

I have verified this by commenting that line out and instead defining fixed values, and the function then runs with no errors.

Here are the transcribed values for how I defined my trigger:

  • Choose which function to run: onFormSubmit
  • Which runs at deployment: Head
  • Select event source: From spreadsheet
  • Select event type: On form submit
  • Failure notification settings: Notify me immediately

Can anyone see what I am doing wrong? Thanks in advance to all who respond.

Leslie
  • 618
  • 4
  • 14
  • 1
    Are you 'manually' running this function from inside Google Apps Script, or are you receiving the error after a form submission? – NEWAZA Mar 14 '23 at 21:31
  • Although I'm not sure about your actual situation, in your situation, is this thread useful? https://stackoverflow.com/q/43429161 – Tanaike Mar 14 '23 at 23:08
  • NEWAZA, thanks for your question. I received the error after a form submission. Tanaike, thank you as well for your question. Your link was relevant and helpful. – Leslie Mar 15 '23 at 16:30

1 Answers1

1

The methods to access the values from the object e varies depending on the trigger. When using the onFormSubmit trigger linked to a spreadsheet the method to use is e.values; this will give you an array with all values answered by the person that submits the form. You can also use e.namedValues; to get an object with the the form title questions as property names. And the form answer as object values.

I recommend you using console logging e to better understand the object structure. Here the Google documentation https://developers.google.com/apps-script/guides/triggers/events#form-submit

Matias CG
  • 411
  • 3
  • 6
  • Matias, thanks for the response. I looked at your link, after changing my function to use statements such as "var FirstName = e.values[0];", my function worked. – Leslie Mar 15 '23 at 16:22