Search code examples
google-apps-script

google form is logging responses, but function in apps script isn't moving data to google sheet?


I have a google form that has logged responses, but isn't sending to linked google sheet? I have the trigger set up on correct function and the event type is On Form Submit. Any ideas what could be happening?

    // This function is triggered when a response is submitted to the Google Form.
    function onSubmit(e) {
      var responses = e.values.slice(1); // Exclude the timestamp from the submitted values
      writeToSheet(responses);
    }

    function writeToSheet(responses) {
      Logger.log('Responses received:', responses); // Add this logging statement
      var ss = SpreadsheetApp.openById('13o5d1AhslmYP3BcO1U16DxkyoCxo44rt7wgOKcq-PeE');
      var sheet = ss.getSheetByName('Sheet1');
      var lastRow = sheet.getLastRow();

      // Write responses to respective columns in the next available row
      sheet.getRange(lastRow + 1, 5, 1, responses.length).setValues([responses]);
    }

Solution

  • Getting Response during OnFormSubmit()

    Your original issue is coming from the 'Null' values. I have created a solution that will take advantage of the ItemResponses() to get the values instead. Due to limited information about your whole use case, I can only create a code that will work as what you have shared and I just made it as close as possible to your code sample this way you can interact with it with ease.

    Sample Code:

    function onSubmit() {
          var form = FormApp.openById("changetoFormID");
          var dataToSheet = [];
          var formResponses = form.getResponses();
          var lastFormResponse = formResponses[formResponses.length - 1]; 
          var itemResponses = lastFormResponse.getItemResponses();
            for (var j = 0; j < itemResponses.length; j++) {
                dataToSheet.push(itemResponses[j].getResponse());
    } 
        writeToSheet(dataToSheet)
        }
    
     function writeToSheet(responses) {
          Logger.log('Responses received:', responses); // Add this logging statement
          var ss = SpreadsheetApp.openById('changeToSheetID');
          var sheet = ss.getSheetByName('Sheet1');
          var lastRow = sheet.getLastRow();
    
          // Write responses to respective columns in the next available row
          sheet.getRange(lastRow + 1, 5, 1, responses.length).setValues([responses]);
        }
    

    Reference:

    Class Item Responses