javascripthtmlgoogle-apps-scriptfile-uploadform-submit

custom contact form google sheet


i tryed this code its almost working. but there is an issue with this code.

whats not working

without uploading file the send button not working.

trying to acheive

all input field should have required(name,email,phone,message). but uploading file must be optional field.

Addditiional : i tryed to add feature like auto sending email to receiver after user submit form successfully. but i unable to code that part,if someone know how to do that is most welcome to add this auto email feature.

here is code i tryed [ (code.gs), (index.html), (library id) ]

library id

 1CcBYkrGSeBRgphHUE92vWInyULOcJ1Ub6eFUR0_gI1h9I6whLjXtDA-P

code.gs

function doGet() {
  return HtmlService.createTemplateFromFile('index').evaluate()
  .addMetaTag('viewport', 'width=device-width, initial-scale=1')
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}

var url = 'google sheet url here'
var sh = 'sheet1'<!-- current google sheet name here -->
var folderId = 'google drive folder id here'

function processForm(formdata){
  var superscript = SuperScript.initSuper(url,sh)
  
  var formObject = {}
  formdata.forEach(element => formObject[element.name] = element.value),
  formdata.forEach(element => formObject[element.message] = element.value)
  formdata.forEach(element => formObject[element.email] = element.value)
  formdata.forEach(element => formObject[element.phone] = element.value)

  var file = superscript.uploadFile(folderId,formObject.myfile.data,formObject.myfilename)
  var ss= SpreadsheetApp.openByUrl(url);
  var ws=ss.getSheets()[0]
   ws.appendRow([
     new Date(),
    formObject.name,
    "'"+formObject.message,
    formObject.email,
    formObject.phone,
    file.getUrl()
  ]);
  };

index.html

<!DOCTYPE html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
        integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  
  
</head>
<body>
    <div class="container py-5">
        <div class="row">
            <div class="col-lg-5 col-md-8 mx-auto shadow border bg-white p-4 rounded">
                <nav class="navbar navbar-dark bg-primary">
                    <a class="navbar-brand" href="#" fw-bold mb-3>WRITE YOUR QUERY / Message</a>
                </nav>
                <br>
                <form id="myForm" onsubmit="handleFormSubmit()">
                    <div id="form_alerts"></div>
                    <div class="form-group mb-3">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" placeholder="Enter your Name here|" name="name"required>
            </div>

            <div class="form-group mb-3">
            <label for="email" >Email</label>
                        <input type="email"  class="form-control" id="email"
            placeholder="Enter your email address here|" name="email" required>
            </div>

            <div class="form-group mb-3">
           <label for="phone">phone number</label><br><br>
  <input type="tel" id="phone" class="form-control" name="phone" placeholder="Enter your phone number here with country code." pattern="[+]{1}[0-9]{2}[0-9]{10}" required><br><br>
  <small>Format: +919234567898</small><br><br>
            </div>

            <div class="form-group mb-3">
              <label for="message">Message</label>
    <textarea class="form-control" id="message" placeholder="Write your message here|" name="message" required ></textarea>
              </div>

                         <div class="form-group mb-3">
                            <label for="uploadFile">Upload File</label>
                            <input type="file" class="form-control" File="file" id="file">
                            </div>
                            <button type="submit" class= "btn btn-primary btn-block">SEND</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
  <script>
        function preventFormSubmit() {
                var forms = document.querySelectorAll('form');
                for (var i = 0; i < forms.length; i++) {
                    forms[i].addEventListener('submit', function (event) {
                        event.preventDefault();
                    });
                }
            }
            window.addEventListener('load', preventFormSubmit);
            function handleFormSubmit() {
                var formdata = $('#myForm').serializeArray()
                formdata.push({
                  name: 'myfile',
                  value: myfile
                })
                google.script.run.withSuccessHandler(success).processForm(formdata);
            }
            function success(){
                 document.getElementById("myForm").reset()
                 Swal.fire({
                  position: 'center',
                  icon: 'success',
                  title: 'sended sucessfully be ready we will contact you shortly',
                  showConfirmButton: true,
      
                })
            }
        var myfile ={},file, reader = new FileReader();
      reader.onloadend = function(e) {
          myfile.data = e.target.result
          myfile.name = file.name
          console.log(myfile)
      };
     $('#file').change(function(){
       file = $('#file')[0].files[0]
        reader.readAsDataURL(file);
     })
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="sweetalert2.all.min.js"></script>
</body>
</html>


Solution

  • Although I'm not sure whether I could correctly understand your expected result, how about modifying your script as follows?

    Modified script:

    In this modification, your Google Apps Script function processForm(formdata) is modified.

    function processForm(formdata) {
      var superscript = SuperScript.initSuper(url, sh);
      var formObject = {};
      formdata.forEach(element => formObject[element.name] = element.value);
      formdata.forEach(element => formObject[element.message] = element.value);
      formdata.forEach(element => formObject[element.email] = element.value);
      formdata.forEach(element => formObject[element.phone] = element.value);
    
      var f = formdata.find(({ name }) => name == "myfile");
      var file = (f && f.value?.name && f.value?.data) ? superscript.uploadFile(folderId, formObject.myfile.data, formObject.myfilename) : "";
      var ss = SpreadsheetApp.openByUrl(url);
      var ws = ss.getSheets()[0];
      ws.appendRow([
        new Date(),
        formObject.name,
        "'" + formObject.message,
        formObject.email,
        formObject.phone,
        file && file.getUrl()
      ]);
    
      // About your request, if you want to send an email, how about using the following script. But, in this case, please set your subject and email body.
      MailApp.sendEmail({ to: formObject.email, subject: "sample subject", body: "sample body" });
    }
    

    This modification works both with and without the uploaded file.

    About your 2nd request i tryed to add feature like auto sending email to receiver after user submit form successfully. but i unable to code that part,if someone know how to do that is most welcome to add this auto email feature., if you want to send an email, how about using the last line in the function processForm. But, in this case, please set your subject and email body. By this, when the button is clicked, an email is sent to the inputted email address.

    Note: