-1

I create google form then connected it with spreadsheet

I created HTML FORM using JS to send data spreadsheet but when I use JS code to post, it returns this error

Access to XMLHttpRequest at 'https://docs.google.com/forms/u/0/d/e/#/formResponse' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 
var fullname=$('#fullname').val();
 
$.ajax({
url:"https://docs.google.com/forms/u/0/d/e/1FAIpQLSfzEDUGgQoEC98bBPCKbvEdei3PWCyLYi3B4pcAfgyfhtr_Qg/formResponse",data:{"entry_1852387181":fullname,"entry_285919830":fullname}
,type:"POST",dataType:"xml"


});
iansedano
  • 6,169
  • 2
  • 12
  • 24
  • Can you check if your data is updated even though you still get the error? Can you provide more details and more code so that we can try to reproduce your error? – iansedano Sep 18 '20 at 11:40
  • Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – Alon Eitan Jul 09 '21 at 06:39
  • I am looking with this I hope I will find the answer. if I found I will answer for your question – Marynathan Judson Jul 09 '21 at 07:17
  • check this YouTube video. it may help you https://youtu.be/6mazxdskiUc – Marynathan Judson Jul 09 '21 at 11:00

1 Answers1

0
your form.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="x-UA-Compatible" content="id=edge">
        <title>formOpene-1 </title>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
        $(document).ready(function(){
          $("form").submit(function(){
          alert("Submitted");
         // $("#mainForm")[0].reset();
          });
          document.getElementById("workSpace").innerHTML = form;
          $("#mainForm")[0].reset();
        });
        </script>
    </head>
    <body>
        
        <div id="workSpace">
            <script>
                form = "";

                form += '<form id="mainForm" action="your web app url" onload="Reset()">';
                form += '<table id="mainTable">';
                form += '<tr>';
                form += '<td class="QandA" id="">';
                form += '<p class="questions">Name of School</p>';              
                form += '<input type="text" id="schoolname" name="SchoolName" class="dropDownAnswers" list="schoollist">';
                form += '</td>';
                form += '</tr>';
                form += '<tr>';
                form += '<td class="QandA" id="">';
                form += '<p class="questions">Date</p>';
                form += '<input type="date" name="Date" class="dateTimeAnswer" id="schoolname" placeholder="date">';
                form += '</td>';
                form += '</tr>';
                form += '<tr>';
                form += '<td class="QandA" id="">';
                form += '<input type="time" name="Time" for="school" class="dateTimeAnswer" id="schoolname" placeholder="date">';
                form += '</td>';
                form += '</tr>';
                form += '<tr>';
                form += '<td class="QandA" id="">';
                form += '<p class="questions">what you do</p>';
                form += '<input type="text" name="Work" for="school" class="textAnswer" id="schoolname" placeholder="date">';
                form += '</td>';
                form += '</tr>';
                form += '<tr>';
                form += '<td class="QandA" id="">';
                form += '<p class="questions">How is work place?</p>';  
                form += '</td>';
                form += '</tr>';
                form += '<tr>';
                form += '<td>';
                form += '<button type="submit"id="submit-form"  >Submit</button>';
                form += '</td>';
                form += '</tr>';
                form += '</table>';
                form += '</form>';
            </script>
        </div>

        <script>
            var $form = $('form#mainForm'),
    
                url = 'https://script.google.com/macros/s/AKfycbzXVpH1ot8OdiHWvJq7bGtfsmH-dw20AhbiTNBP6iuAic043neaXjIIoxaEyee1pLkRVA/exec'
            
        $('#submit-form > input').on('click', function(e) {
          e.preventDefault();
          var jqxhr = $.ajax({
            url: url,
            method: "GET",
            dataType: "json",
            data: $form.serializeObject()
          }).success(
            // do something
            Console.log("success")
          );
        });
        
        </script>
    
    </body>
</html>

your code.gs


// original from: http://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
// original gist: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6 

function doGet(e){
  return handleResponse(e);  
}

//  Enter sheet name where data is to be written below
        var SHEET_NAME = "Sheet1";

var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

function handleResponse(e) {
  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.
  
  try {
    // next set where we write the data - you could write to multiple/alternate destinations
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    var sheet = doc.getSheetByName(SHEET_NAME);
    
    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    var headRow = e.parameter.header_row || 1;
    var headers = sheet.getRange(1, 5, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = []; 
    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(new Date());
      } else { // else use header name to get data
        row.push(e.parameter[headers[i]]);
      }
    }
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 5, 1, row.length).setValues([row]);
    sheet.getRange(nextRow, 2).setValue(new Date());
    serialNodata = sheet.getRange(nextRow-1, 1).getValue();
    serialNo = serialNodata+1;

    sheet.getRange(nextRow, 1).setValue(serialNo);
    user = Session.getActiveUser();
    user1 = Session.getEffectiveUser();
    loginId = Session.getUser().getUserLoginId();
    loginIdEfectiv = Session.getEffectiveUser().getUserLoginId
    
    sheet.getRange(nextRow, 10).setValue(loginId);
    sheet.getRange(nextRow, 11).setValue(loginIdEfectiv);
    sheet.getRange(nextRow, 3).setValue(user);
    sheet.getRange(nextRow, 4).setValue(user1);
    Logger.log(user);

    lastRecord = sheet.getRange(nextRow-1, 5, 1,5).getValue();
    currentRecord = sheet.getRange(nextRow, 5, 1, 5).getValue();
    nextColumn = sheet.getLastColumn()+1;
    if(lastRecord == currentRecord) {
      sheet.getRange(nextRow, 1, 1, nextColumn).clear();
    }

   
    // return json success results
   // return ContentService

  
    return HtmlService.createHtmlOutputFromFile("form");
  } catch(e){
    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  } finally { //release lock
    lock.releaseLock();
  }
}

function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
}






your message.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  <h3>your record was recorded  </h3>
    
  </body>
</html>