How to send data from HTML form to Google Spreadsheet using JavaScript?

Simone

I'm trying to build a webapp that records datas from a form in a Google Spreadsheet. To do this, I have to use JavaScript (JSON or AJAX requests will work as well), but I cannot use Google Apps Script because I need the user to keep using my pages and GAS doesn't allow it.

I'm not so much versed in JSON requests but I tried to make an append one: no surprise, it's not working and no surprise, I don't know why.

I'm not sure the URL I used to make the request and the code are correct, but not knowing very well how to proceed, it's quite difficult to know what's wrong in my code.

That's my form:

    <form name="reqForm" id="reqForm" method="post" action="" accept-charset="UTF-8" enctype="application/json">
            <input type="hidden" name="area" id="area" readonly/>
            <input type="hidden" name="idN" id="idN" readonly/>
            <input type="hidden" name="dataReq" id="dataReq" readonly />
            <label for="nome">* Nome:</label>
            <input type="text" id="nome" name="nome" placeholder="Il tuo nome" />
            <label for="cognome">* Cognome:</label>
            <input type="text"  id="cognome" name="cognome" placeholder="Il tuo cognome" />
            <label for="mat">* Matricola:</label>
            <input type="text" id="mat" name="mat" placeholder="La tua matricola" />
            <label for="mail">* E-mail:</label>
            <input type="text" id="mail" name="mail" placeholder="La tua e-mail" />
            <label for="testo">* Richiesta:</label>
            <textarea id="testo" name="testo" placeholder="Che cosa vuoi chiedere?"></textarea>
            <button type="button" value="Invia" onClick="check()">Invia</button>
        </form>`

The hidden values are set to provide an ID Number and the user's path.

The check() function will check the form and (should) make the request and write in the GSpreadSheet

    function check() {

document.getElementById('errorForm').innerHTML = "";

var a = document.getElementById('area').value;
var idN = document.getElementById('idN').value;
var n = document.getElementById('nome').value;
var c = document.getElementById('cognome').value;
var m = document.getElementById('mat').value;
var em= document.getElementById('mail').value;
var t = document.getElementById('testo').value;

// check the possible errors and set error messages.
    // if msg is not empty, writes the messages in my page.

} else if(msg == "") {
    var xhr = new XMLHttpRequest();
    var key = mySheetKey, sName =  mySheetName, url = "https://sheets.googleapis.com/v4/spreadsheets/"+key+"/values/"+ sName + ":append?valueInputOption=USER_ENTERED";

    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4 && xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
        }
    // Here I should create the object made of my variables I read 
    // from my form at the beginning of the code and send the request that
    // should append my datas to my Spreadsheet

    xhr.send();
    } 
    }

As I said before, my code look similar to several ones I found online but it's not working and I don't know how to understand what's wrong.

Could you please kindly give me some tips or advice or some example that could help me appending data to a Google Spreadsheet?

Cooper

A simple spreadsheet contained web app example

$(function() {
        $('#btn1').click(validate);
        $('#txt4').val('');
        $('#txt3').val('');
        $('#txt2').val('');
        $('#txt1').val('')
      });
function validate()
{
    var txt1 = document.getElementById('txt1').value || ' ';
    var txt2 = document.getElementById('txt2').value || ' ';
    var txt3 = document.getElementById('txt3').value || ' ';
    var txt4 = document.getElementById('txt4').value || ' ';
    var a = [txt1,txt2,txt3,txt4];
    if(txt1 && txt2 && txt3 && txt4)
    {
      google.script.run
        .withSuccessHandler(setResponse)
        .getData(a);
        return true;
    }
    else
    {
      alert('All fields must be completed.');
    }
}

The entire example:

The HTML:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  <div id="data">
    <br />Text 1<input type="text" size="15" id="txt1" />
    <br />Text 2<input type="text" size="15" id="txt2" />
    <br />Text 3<input type="text" size="15" id="txt3" />
    <br />Text 4<input type="text" size="15" id="txt4" />
    <br /><input type="button" value="submit" id="btn1" />
  </div>
  <div id="resp" style="display:none;">
    <h1>Response</h1>
    <p>Your data has been received.</p>
  </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      $(function() {
        $('#btn1').click(validate);
        $('#txt4').val('');
        $('#txt3').val('');
        $('#txt2').val('');
        $('#txt1').val('')
      });

      function setResponse(a)
      {
        if(a)
        {
          $('#data').css('display','none');
          $('#resp').css('display','block');
        }
      }

      function validate()
      {
        var txt1 = document.getElementById('txt1').value || ' ';
        var txt2 = document.getElementById('txt2').value || ' ';
        var txt3 = document.getElementById('txt3').value || ' ';
        var txt4 = document.getElementById('txt4').value || ' ';
        var a = [txt1,txt2,txt3,txt4];
        if(txt1 && txt2 && txt3 && txt4)
        {
          google.script.run
            .withSuccessHandler(setResponse)
            .getData(a);
            return true;
        }
        else
        {
          alert('All fields must be completed.');
        }
      }

      function loadTxt(from,to)
      {
          document.getElementById(to).value = document.getElementById(from).value;
      }

     console.log('My Code');
   </script>
  </body>
</html>

The Apps Script:

function getData(a)
{
  var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'HH:mm:ss");
  a.push(ts);
  SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Login').appendRow(a);
  return true;
}

function doGet()
{
  var html = HtmlService.createHtmlOutputFromFile('index');
  return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)

}

My simple spreadsheet:

enter image description here

The good news is that you're probably a lot better at using the Google Chrome debugger now than before you started.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Is it possible to 'prefill' a google form using data from a google spreadsheet?

From Dev

How to get data from html form using Google App Script

From Dev

updating existing data on google spreadsheet using a form?

From Dev

how return data from HTML service (UI) to google spreadsheet

From Dev

How to retrieve data from Google Spreadsheet to Javascript or JSON?

From Dev

How to read data from a private google spreadsheet in javascript -- Nov 2014?

From Dev

Google Apps Script HTML Form - Put Data into Spreadsheet using Variables for Form Fields

From Dev

How to extract data from Google spreadsheet by using REGEXEXTRACT regex

From Dev

Edit data in a Google Spreadsheet, via a form of sorts or alert box, using data from a script

From Dev

Send Email from Feedback form WebPage using JavaScript and HTML

From Dev

How to use a html form to send data to javascript to be saved as a variable

From Java

how to get the data from the spreadsheet and send it to an html table googel script web

From Java

How to send a JSON object using html form data

From Dev

How to send and store data in an XML file, using an HTML form?

From Dev

Add basic data to a Google Spreadsheet via a simple HTML Form

From Dev

Google HTML Service: write values from multiple selects in form to spreadsheet

From Dev

Display a cell value from google spreadsheet on HTML form input

From Dev

Google Form - Spreadsheet and data insertion

From Dev

How to send json serialize data from a form to ajax using django

From Dev

HTML form: send data to javascript function

From Dev

How do i get the date value from google spreadsheet database using javascript in google app script

From Dev

How do I write data from a google spreadsheet into a time input field in a templated html file

From Dev

send data link from modal to form with javascript

From Dev

How do I input text via an HTML form and retrieve data from a JSON file as a response using Javascript?

From Dev

google apps script html select options loaded from spreadsheet data

From Dev

google apps script html select options loaded from spreadsheet data

From Dev

How to send data from Json using Ajax in jquery for html element?

From Dev

How to send html form data with jquery

From Dev

How to send data from one .window to another using javascript?

Related Related

  1. 1

    Is it possible to 'prefill' a google form using data from a google spreadsheet?

  2. 2

    How to get data from html form using Google App Script

  3. 3

    updating existing data on google spreadsheet using a form?

  4. 4

    how return data from HTML service (UI) to google spreadsheet

  5. 5

    How to retrieve data from Google Spreadsheet to Javascript or JSON?

  6. 6

    How to read data from a private google spreadsheet in javascript -- Nov 2014?

  7. 7

    Google Apps Script HTML Form - Put Data into Spreadsheet using Variables for Form Fields

  8. 8

    How to extract data from Google spreadsheet by using REGEXEXTRACT regex

  9. 9

    Edit data in a Google Spreadsheet, via a form of sorts or alert box, using data from a script

  10. 10

    Send Email from Feedback form WebPage using JavaScript and HTML

  11. 11

    How to use a html form to send data to javascript to be saved as a variable

  12. 12

    how to get the data from the spreadsheet and send it to an html table googel script web

  13. 13

    How to send a JSON object using html form data

  14. 14

    How to send and store data in an XML file, using an HTML form?

  15. 15

    Add basic data to a Google Spreadsheet via a simple HTML Form

  16. 16

    Google HTML Service: write values from multiple selects in form to spreadsheet

  17. 17

    Display a cell value from google spreadsheet on HTML form input

  18. 18

    Google Form - Spreadsheet and data insertion

  19. 19

    How to send json serialize data from a form to ajax using django

  20. 20

    HTML form: send data to javascript function

  21. 21

    How do i get the date value from google spreadsheet database using javascript in google app script

  22. 22

    How do I write data from a google spreadsheet into a time input field in a templated html file

  23. 23

    send data link from modal to form with javascript

  24. 24

    How do I input text via an HTML form and retrieve data from a JSON file as a response using Javascript?

  25. 25

    google apps script html select options loaded from spreadsheet data

  26. 26

    google apps script html select options loaded from spreadsheet data

  27. 27

    How to send data from Json using Ajax in jquery for html element?

  28. 28

    How to send html form data with jquery

  29. 29

    How to send data from one .window to another using javascript?

HotTag

Archive