Store form data on a site in Google Spreadsheets

apps script Apr 7, 2022
 Store form data on a site in Google Spreadsheets

Google sheets are very easy to use and accessible from any device. Google has a very powerful Apps Script tool that allows you to integrate with almost all google products, we use this to save the data from the form on the site directly to the table.

First, what you need to do is create the table itself.
Next, go to Extensions -> App Script

Insert the code 

function doGet(e){
    console.info(e)
    setData(e)
}

function doPost(e){
  if(e.postData.contents)
    e.parameter =  JSON.parse(e.postData.contents)
    setData(e)
}
/**
 * set data request
 */
function setData(e) {
    try {      
      var ss = SpreadsheetApp.openById("1Y3PххххххххххVM7h9WCekM8"); // Change to your table ID 
      // тут ставимо співвідношення Назвпи параметру до колонки в таблиці   
      var column = {
        'name':'B',
        'text':'C'
      }
      var last = ss.getLastRow() + 1;
      for (var param in column){
          if (e.parameter[param]) ss.getRange(column[param] + last).setValue(e.parameter[param]);
      }
 // Set the current date
      ss.getRange('A' + last).setValue(new Date());     

        // ss.getRange(last + ':' + last).setBackground('yellow');//  yellow Background
    } catch (e) {        
        console.log(e.message)
    } 
}

The first thing to do 

  • Change the id to your table id 
  • Adjust the columns according to your query parameters (The example of the query will be clear later)
  • We put our script into effect and copy the Commissioning ID

Example of

JS queries

let data = {
   name : 'Mark',
   text : 'Text message'
}
fetch('https://script.google.com/macros/s/{Ідентифікатор введення в дію}/dev',{
    method: 'POST',
     headers: {
      'Content-Type': 'application/json'      
    },
    body: JSON.stringify()
}).then( res=>{
    res.json().then(r=>{
        console.log(r)
    })
} )

PHP

  $array  =  array ( 
            'name'  =>  'admin' , 
            'text'  =>  '1234' 
        ) ; 
            
        $id  =  '{Activation ID}' ;   
        $url  =  sprintf ( 'https://script.google.com/macros/s/%s/exec' , $id ) ; 
        
        $ch  =  curl_init ( $url ) ; 
        $payload  =  json_encode ( $array ) ; 
        curl_setopt ( $ch ,  CURLOPT_POST ,  1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $html = curl_exec($ch);
        curl_close($ch);

        echo $html;