Search code examples
google-apps-scriptgoogle-forms

Get the last response from a Google Form


I am working on a script to get the last form submission. I found the vanilla example online...

function onSubmit() {
  // Open a form by ID and log the responses to each question.
 var form = FormApp.openById('1G3e4FTYlsJUl5mKX2v1pYWauG1FO5IUPDIOI6P4hUoA');
 var formResponses = form.getResponses();
 for (var i = 0; i < formResponses.length; i++) {
   var formResponse = formResponses[i];
   var itemResponses = formResponse.getItemResponses();
   for (var j = 0; j < itemResponses.length; j++) {
     var itemResponse = itemResponses[j];
     Logger.log('Response #%s to the question "%s" was "%s"',
         (i + 1).toString(),
         itemResponse.getItem().getTitle(),
         itemResponse.getResponse());
   }
 }
}

I have modified this to...

function onSubmit() {
  // Open a form by ID and log the responses to each question.
 var form = FormApp.openById('1G3e4FTYlsJUl5mKX2v1pYWauG1FO5IUPDIOI6P4hUoA');
 var formResponses = form.getResponses();

 var last_response = formResponses[formResponses.length - 1];
  Logger.log(last_response.val)
}

When I view the log for the script above I get undefined. How do I output the value of last_response?


Solution

  • First you need to use the getItemResponses() method. The getItemResponses() method gets all the "Items" of one Form submission. Most of the Items are the questions. But there are Items that are not questions, like PAGE_BREAK. So you need to exclude things like page breaks. I've called the Items in this code Questions, but Items are not always questions.

    function getArrayOfOneSubmissionsAnswers() {
      var allQuestions,i,itemType,L,thisAnswer,thisQuestion,thisSubmissionsAnswers;
        //Define all variables without assigning a value - value at this point
        //is undefined
    
      allQuestions = FormApp.openById('your_Form_ID').getResponses()[0].getItemResponses();
    
      L = allQuestions.length;//How many questions are there in the Form
      thisSubmissionsAnswers = [];//Create an empty array for answers
    
      for (i=0;i<L;i++) {//Loop through all the questions in this Form submission
        thisQuestion = allQuestions[i];//Get this question
    
        itemType = thisQuestion.getItem().getType();
    
        if (itemType === FormApp.ItemType.PAGE_BREAK) {
          continue;//keep looping
        };
    
        thisAnswer = thisQuestion.getResponse();//Get the answer
        Logger.log(i + " - " + thisAnswer); 
    
        thisSubmissionsAnswers.push(thisAnswer);//add answer to the array
      };
    
      Logger.log("thisSubmissionsAnswers: " + thisSubmissionsAnswers); 
    
      return thisSubmissionsAnswers;
    };