K
K
Kaunov_ivan2015-07-29 16:11:18
JavaScript
Kaunov_ivan, 2015-07-29 16:11:18

How to send javascript data to google sheets?

Task: make a contact form without using any backend. Sending an AJAX request to a script in a Google spreadsheet and saving the data in a Google spreadsheet.
html:

<textarea type="text" id="question" class="form-control text-size input-group-lg-v" name="question"></textarea>
   <input type="text" class="form-control" id="mail" name="email">
   <button class="btn btn-info btn-sm span-btn" type="submit" onclick="sendQuestion()"> Отправить </button>

js:
function sendQuestion() {
    var email = $('#mail').val();
    var question = $('#question').val();
    if(email == ''){
      alert('Вы не ввели E-mail!');
      return false;
    };
    $.ajax({
          type: 'POST',
          url: 'http://script.google.com/macros/s/AKfycbz6tFgfpy3JzBGXVL3O0GsZPNVN9l9GPr7ZXT6Oo_IfB9GC-4E/exec',
          data: {'email'    : email,
           'question' : question},
          cache: false,
          success: function(data){
        console.log("success: "+data);
          },
      error: function(err){
        console.log("error: "+err)
      }
      });
    alert("Спасибо! Ответ будет отправлен на e-mail "+email);
  };

google script:
function doGet(e){
  var sheet = SpreadsheetApp.openById("1iZazQ8YSMa6b9WFKTHJ99WooEC48nH9IF1x9fh6dQ9Y");
  obj = JSON.parse(e.parameter.p1);
  sheet.appendRow(obj);
}

at this stage, it gives an error when sending a request:

XMLHttpRequest cannot load https://script.google.com/macros/s/AKfycbz6tFgfpy3... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' zolpol-local2 ' is therefore not allowed access.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
MhMadHamster, 2015-07-29
@MhMadHamster

You are trying to use ajax cross-domain, but the security policy restricts it in such a way that you can only ajax to the same domain, try using JSONP to solve your problem

A
Alexander Ivanov, 2015-08-09
@oshliaer

  1. Your function in the Google Apps Script server does not return anything.
  2. Your Google Apps Script server is expecting a GET request.

Server code
function doPost(e){
  var response = {};
  try {
    var sheet = SpreadsheetApp.openById('1iZazQ8YSMa6b9WFKTHJ99WooEC48nH9IF1x9fh6dQ9Y');
    sheet.appendRow([new Date(), JSON.stringify(e)]);
    response = {'result': 'OK'};
  } catch(err) {
    response = {'error': 'error'};
  } finally {    
    return ContentService.createTextOutput(JSON.stringify(response)).setMimeType(ContentService.MimeType.JSON);
  }
}

  • Checking, suddenly, something does not work gscorstest
  • Sample solution plnkr.co/3XgR57KMCW9dzP8rkLCD

Sincerely.

S
Sebring, 2017-03-02
@Sebring

Hello, the solution example also gives "No 'Access-Control-Allow-Origin' header is present"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question