Input various information into a single form multiple times and automatically submit it to a Google spreadsheet

I have some data that needs to be transferred to an array and then sent to a Google Sheet. The data looks like this: -|PO: 2005 | 12121211212121,| Qty: 45| BIN:110| eBay| 11/6/2017-| PO: 2165 | 333333333,| Qty: 54| BIN:20| google| 11/6/2017-

First, I use JavaScript to transfer the data to an array, then put all the data from the array into a form and click submit.

Here is what the array looks like:

(6) ["PO: 2005 ", " 12121211212121,", " Qty: 45", " BIN:110", " eBay", " 11/6/2017"] index.html:62 (6) [" PO: 2165 ", " 333333333,", " Qty: 54", " BIN:20", " google", " 11/6/2017"]

The form should be submitted multiple times, but only the data for the first entry is showing up on the Google Sheet.

This code snippet below shows my main HTML structure:

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

//  
$(document).ready(function() {
    //
    $('#googleSheetInsert').bootstrapValidator({
        //submitButtons: '#postForm',
        // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },  
    })
    .on('success.form.bv', function(e) {
        // Prevent form submission
        e.preventDefault();

        // Get the form instance
        var $form = $(e.target);

        // Get the BootstrapValidator instance
        var bv = $form.data('bootstrapValidator');

        // Use Ajax to submit form data
        var url = ' ';
        var redirectUrl = 'index.html';
        // show the loading 
        $('#postForm').prepend($('<span></span>').addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate'));
        var jqxhr = $.post(url, $form.serialize(), function(data) {
            console.log("Success! Data: " + data.statusText);
           // $(location).attr('href',redirectUrl); relocation
        })
            .fail(function(data) {
                console.warn("Error! Data: " + data.statusText);
                // HACK - check if browser is Safari - and redirect even if fail b/c we know the form submits.
                if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
                    //alert("Browser is Safari -- we get an error, but the form still submits -- continue.");
                    $(location).attr('href',redirectUrl);                
                }
            });
    });
});
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <link href="http://cdn.jsdelivr.net/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="http://cdn.jsdelivr.net/fontawesome/4.1.0/css/font-awesome.min.css" />
    
    <link rel="stylesheet" href="http://cdn.jsdelivr.net/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css"/>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    
    <script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.bootstrapvalidator/0.5.0/js/bootstrapValidator.min.js"></script>
    <style type="text/css">
      body {
        margin: 10px;
        white-space: nowrap;
      }

      h1 {
        font-size: 15px;
      }

      #container {
        align-items: center;
        display: flex;
        justify-content: space-between;
      }
    </style>
    <!--
      - JavaScript and HTML must be in separate files: see our Content Security
      - Policy documentation[1] for details and explanation.
      -
      - [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
    -->
<script>
        
        function submitDataToGoogleSheet(){
            var dataFromInput = document.getElementById("SOS_POData").value;
            // Split by -| and put to array
            var filter0 = dataFromInput.split("-|");
            // Remove Empty Element
            var unitArray =[]; 
            for(var i=0;i<filter0.length;i++){
                if(filter0[i]!==""){
                    unitArray.push(filter0[i].split("|")); 
                }
            }
            // insert data to google sheet
            
            for(j=0;j<unitArray.length;j++){
            doSubmite(unitArray,j);
            }
         
        }
        
        function doSubmite(unitArray,j){
            console.log(unitArray[j]);
            document.getElementById('PO_Number').value = ((unitArray[j][0]).substring(4)).replace(/(^\s*)|(\s*$)/g,"");
            document.getElementById('Part_Number').value = (unitArray[j][1]).replace(/(^\s*)|(\s*$)/g,"");
            document.getElementById('Qty').value = ((unitArray[j][2]).substring(5)).replace(/(^\s*)|(\s*$)/g,"");
            document.getElementById('BIN').value = (unitArray[j][3]).substring(5);
            document.getElementById('Receiver_Name').value = (unitArray[j][4]).replace(/(^\s*)|(\s*$)/g,"");
            document.getElementById('Receiver_Data').value = (unitArray[j][5]).replace(/(^\s*)|(\s*$)/g,"");
            document.getElementById('postForm').click();
            
        }
         
  </script>
  </head>

  <body>
    <h1>Please copy all information from label in there.</h1>
    <div id="container">
      
      <form id="dataFromSOS" action="#" method="post">
          <input type="text" name="SOS_POData" id="SOS_POData" required="" placeholder="Please copy all label information in there">
          <input type="button" name="submit_form" value="Submit" onclick="submitDataToGoogleSheet()"> 
      </form >
    </div>
    
    <div>
        <form id="googleSheetInsert">
            <label>PO</label>
            <input id='PO_Number' name='PO_Number' type='text'>  
            <label>PartNumber</label>
            <input id='Part_Number' name='Part_Number' type='text'>
            <label>Qty</label>
            <input id='Qty' name='Qty' type='text'>
            <label>BIN</label>
            <input id='BIN' name='BIN' type='text'>
            <label>Receiver_Name</label>
            <input id='Receiver_Name' name='Receiver_Name' type='text'>
            <label>Receiver_Data</label>
            <input id='Receiver_Data' name='Receiver_Data' type='text'>
            <input type="submit"   name="submit" id="postForm"  />
        </form>
        
        
    </div>
    
    <script src="js/sendDataToGoogleSheedAjax.js"></script>
     
  </body>
</html>

Answer №1

Have you configured your Google Sheet to handle simultaneous form submissions?

You can refer to the example link below for guidance:
https://medium.com/@dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952cc175

It seems like your multiple submits are working correctly based on my observation (without a specific sheet to submit to). When analyzing the code, I noticed that the form is being updated with values and parsed appropriately. This leads me to believe that the issue may lie on the recipient's end.

To make it function properly, I followed these steps:

  1. Ensure that the names in the Google Sheet columns match with the <input name=""> in the form.
  2. In Google Sheets, go to Tools->Script editor and paste the script from this link: https://gist.github.com/mhawksey/1276293
  3. In the script editor, go to Run->Run Function->setup
  4. In the script editor, go to Publish->Deploy as web app...
    • Adjust the security level and enable service (probably execute as 'me' and access 'anyone, even anonymously')
    • Note the URL for future POST requests
    • The URL format should be like
      https://script.google.com/macros/s/<GIBERISH>/exec
  5. Update how you call the ajax POST function (I encountered issues with bootstrap validator, so I removed it and everything worked as intended.)

Here's an example of the code:

$('#googleSheetInsert').on('submit', function(e) {
      // Prevent form submission
      e.preventDefault();

      // Get the form instance
      var $form = $(e.target);

      // Use Ajax to submit form data
      var url = 'https://script.google.com/macros/s/<GIBERISH>/exec';
      var redirectUrl = 'index.html';
      // Show loading icon 
      $('#postForm').prepend($('<span></span>').addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate'));
      var jqxhr = $.post(url, $form.serialize(), function(data) {
          console.log("Success! Data: " + data.statusText);
        // $(location).attr('href',redirectUrl); relocation
      })
          .fail(function(data) {
              console.warn("Error! Data: " + data.statusText);
              // Redirect if browser is Safari even on fail as form still submits
              if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
                  $(location).attr('href',redirectUrl);                
              }
          });
  });

Images illustrating the functional code:

Submitting test data multiple times
Updated form appearance

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

To activate a function, simply click anywhere on the body: instruction

One of my latest projects involved creating a directive that allows users to click on a word and edit it in a text box. Once edited, clicking anywhere on the body should return the word back to its updated form. html <div markdown>bineesh</div& ...

What is the best way to convert a date to ISO 8601 format using JavaScript? Are there any built-in functions or methods in

Currently, I am using this function to set the duration: const setDuration = () => { const currentDate = new Date(); const newDate = new Date(currentDate.getTime()); const year = newDate.getUTCFullYear(); const m ...

Submit form using jQuery after making an AJAX request with jQuery's $

I'm working on the following code: $.get(link, function(data, status) { document.getElementById("test").value = data; }); $('#formtest').submit(); Everything works fine in Firefox, but in Google Chrome the submit is done before t ...

What is the best way to extract a CSS rule using PHP?

Below is an example of the stylesheet I am currently using: #thing { display: none; } I am looking to retrieve the value of the 'display' property using PHP instead of Javascript. While I know how to do this with Javascript, I would prefer to u ...

Generating a single JSON record in React Native

Need help displaying a single JSON record from an API request on the screen. const [user, setUser] = useState(); const getUserData = async () => { // {headers: {Authorization: "Basic " + base64.encode(username + ":" + passwor ...

Enhance and streamline custom module code within a Node.js Express application

I am seeking suggestions on how to optimize the code within my custom module. Below is the code for my module which you can review and provide feedback on. var employee = { all: function (req, res) { jwt.verify(req.token, 'novatureso ...

Create a React component using the value stored within an object

I am interested in creating an object: import React from "react"; import { Registration } from "../../"; const RouteObj = { Registration: { route: "/registration", comp: <Registration /> } }; export default RouteObj; Next, in a separat ...

Replacing one <div> with another <div> using a clickable link within the divs

In one of my web pages, there is a div that I'll refer to as div1. Within this div, there is a link called 'Link1'. My goal is to click on Link1, triggering the replacement of div1 with div2. Inside div2 there will be another link, let&apos ...

Unable to access the inner object using key-value pair in Angular when working with Firebase

Within my json object, there is an inner object labeled data, containing {count: 9, message: "9 sites synced"} as its contents - also in json format. My objective is to extract the value from message, rather than count. Provided below is the temp ...

Use JavaScript to limit Google Analytics and Yandex.Metrica to track only the referral sources and screen sizes

I prefer not to include external JavaScript on my website for unnecessary tracking purposes. However, I do need to gather referrer and screen size information, which cannot be achieved with a regular HTML img tag alone. What is the most standard-complian ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

I encountered an issue while iterating through Object HTMLDivElement and applying ChileNode style z-index, resulting in an undefined output in both Firefox and Chrome browsers

function adjustPosition(currentDiv) { try { for (var i = 0; i < document.getElementById("parentContainer").childNodes.length; i++) { document.getElementById("parentContainer").childNodes[i].style.zIndex = 0; ...

AJAX and Python conflict - The requested resource is missing the 'Access-Control-Allow-Origin' header

I am currently developing a unique JavaScript library that has the capability to communicate with a basic Python web server using AJAX. Below is the snippet for the web server class: class WebHandler(http.server.BaseHTTPRequestHandler): def parse_PO ...

Display solely the error message contained within the error object when utilizing the fetch API in JavaScript

I am facing an issue in logging the error message to the console while everything else seems to be working fine. Specifically, I am unable to log only the message such as "email exists" when the email already exists in the system. const submitHandler = a ...

Tips for sending an array to an action method in ASP.Net MVC

Currently, I am working on an ASP.Net MVC5 project where I am attempting to send JSON data to the controller's action method via an AJAX request. The JSON data consists of various form values. To facilitate a master-detail form structure with one-to-m ...

What is the best way to import modules with the "@" symbol in their path when working with Node.js?

Situation In my VueJS project, I have created service modules for use with vue cli. My code makes use of the @ symbol to easily access files within the src folder: /* Inside someService.js */ import API from '@/services/APIService.js' Ch ...

What is the best way to display the value of a new object's property in Angular?

I am currently developing a list application that allows users to create new lists by entering a name and clicking a button. Once the list is created, users can add and remove items from the list. However, I have encountered an issue where the name of the ...

Locating a record within a database that contains an objectId field linking to a separate collection

I have defined two collections in the following manner const BookSchema = new mongoose.Schema({ title: String, author: { type: mongoose.Object.Types.ObjectId, ref: "author" } }) const BookModel = mongoose.model(" ...

Running a CSS keyframes animation can be achieved by removing the class associated with it

Is there a way to reverse the CSS animation when a class is removed? I'm trying to achieve this on my simple example here: https://codepen.io/MichaelRydl/pen/MWPvxex - How can I make the animation play in reverse when clicking the button that removes ...

Establishing an RSS feed (Google shopping) for an online store built on Vue-storefront

I recently launched a Vue-storefront based online store and now I'm looking to set up Google Shopping ads using an RSS feed for my products. However, I've encountered an error message saying "Unexpected token < in JSON at position 0" when tryi ...