Shihan Khan
Shihan Khan

Reputation: 2188

Pass value from ajax to Google Apps Script

I'm new to Google Apps Script and I'm trying to make a web app where I can pass the value from Ajax to my script's web app. I'm able to execute it directly from the web app but it's not working from my webpage. Here are my codes,

Webpage's JS

$(document).ready(function () {
  $('#btnGet').click(function () {
    var getId = $('#text').val();
    $.ajax({
      url: "https://script.google.com/macros/s/AKfycbwpkBW7qKZBeJ011C7j3le4vV8D0SEHu9709mWtEMzJgrJmHnaR/exec",
      data: getId,
      type: "GET",
      crossDomain: true,
      success: function (data) {
        console.log(data);
        alert("Success!");
      },
      error: function (data) {
        console.log(data);
        alert("Failed!");
      }
    });
  });
});

Google Apps Script

function doGet(e) {
  var html ="<input type='text' id='text' /><br><br><input type='button' id='btnGet' onclick='myClick()' value='submit' /><br><br>";
  html+="<script>";
  html+="document.getElementById('btnGet').onclick = function() { var e = document.getElementById('text').value; google.script.run.newEntry(e); }</script>";
  return HtmlService.createHtmlOutput(html);
}

function newEntry(text) {
  Logger.log(text);
  var ss = SpreadsheetApp.openById(text);
  var sheet = ss.getSheetByName("Sheet1");
  var lr = sheet.getLastRow();
  sheet.getRange(lr+1, 1, 1, 3).setValues([["First Name", "Last Name", "Email"]]);
}

How can I pass the value from ajax to my apps script?

Upvotes: 0

Views: 1836

Answers (2)

Raghvendra Kumar
Raghvendra Kumar

Reputation: 1398

You will have to make a page redirection and navigate to the script's published url on a click or something

because XHR requests to the Google Apps Script server are forbidden

From an external client XHR requests are forbidden but within the Google App Script editor calls to server side scripts(i.e. any one of the functions in .gs file) are by default asynchronous and can be made using google.script.run

For more please refer to the official documentation.

Google App Script Restrictions

Upvotes: 0

Bryan P
Bryan P

Reputation: 5051

Try appending the data you're sending out onto the end of the url:

"ScriptUrl/exec?getIdKey=getIdValue"

Docs for that.

Your data property is likely just being ignored.

The value can then be accessed in doGet(e) with:

var getIdValue = e.parameter.getIdKey

Docs for that

Upvotes: 2

Related Questions