Submitting data to google sheet with multiple tab sheets - ajax

I'm referencing this article "How to Submit an HTML Form to Google Sheets…without Google Forms", it worked perfectly for me for only a Google Sheet with one tab.
Need help how to dynamically select what sheet tab the data should be written in the case the google sheet has multiple tabs. I'm using Ajax to submit google sheet btw.
Here's the call by the Ajax:
var $form = $('form#test-form'),
url = 'https://script.google.com/macros/s/MyScript/exec'
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(
// do something
);
})
The code on google sheet web app
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, 1, 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, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} 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());
}
If there is a way to change the variable SHEET_NAME dynamically then I think it will be good. Thanks

Related

Cannot correctly get form data in google script

I try to submit form data to google sheet via ajax but google script if else statement not work.
Below is the google script
// 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
// Enter sheet name where data is to be written below
var SHEET_NAME = "Records";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function doGet(e){
return handleResponse(e);
}
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, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
switch (headers[i]) {
case "Timestamp":
row.push(new Date());
break;
case "LogTime":
row.push(new Date());
break;
default:
row.push(e.parameter[headers[i]]);
break;
}
}
// more efficient to set values as [][] array than individually
sheet.appendRow(row);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} 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());
}
I submit the form data using ajax
HTML
<form id="checkin-form">
<input type="hidden" name="Event" value="<?php echo $events[1]; ?>"/>
<input type="hidden" name="LogTime" value="" />
...
</form>
Javascript
$('#checkin-form').on('submit', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
crossDomain: true,
url: url,
method: "GET",
dataType: "json",
data: $("#checkin-form").serialize()
});
return false;
});
From google script, the column LogTime cannot get the Date() but keep empty. What is the possible issue?
Here is the google sheet column
Best regards,
Kelvin
Don't know why the google apps script does not work, finally, I found the article from https://medium.com/#dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952cc175, when I redo running the Setup function, everything works properly. The Setup function has already been run before and the script worked.

Problem with scope when inserting results of ajax call into page code

I have data returned from an Ajax call, but need to pass variables into or out of the Ajax onSuccess function to insert the results into my page. I'm pretty sure this is a scope problem.
I posted a complicated question here yesterday, mostly about the Ajax part of this, and that part is now working - I'm getting the results back correctly. I could insert it into my page code in two ways, but one involves getting a variable value out of the onSuccess function; the other needs to get a variable value into it! I can't make either of them work. Here's a stripped-down version of the code:
var base = 'http://10.0.1.2:90/~dvds/';
// initialization routines
document.observe ('dom:loaded', function() {
// set up handler for variable numbers of selects
var addselects = $$('.addselect');
for (var i = 0; i < addselects.length; i++) {
var addselect = addselects[i];
addselect.onchange = newSelect;
}
});
// handler for adding new field to array
function newSelect() {
var thisid = this.id;
var newhtml;
var url = base + 'ajaxtest';
// send request to do the business
var myAjax = new Ajax.Request (url, {
method: 'post',
onSuccess: function (req) {
var xml = req.responseXML;
var id = xml.getElementsByTagName('id')[0].firstChild.nodeValue;
if (id) {
newhtml = '\t\t<li>\r\t\t\t<select class="addselect" name="newlist" id="newlist" />\r\t\t\t\t<option value="" selected="selected"></option>\r';
// loop
var newid, newname;
var ids = xml.getElementsByTagName('id');
var names = xml.getElementsByTagName('name');
for (var i = 0; i < ids.length; i++) {
newid = ids[i].firstChild.nodeValue;
newname = names[i].firstChild.nodeValue;
newhtml += '\t\t\t\t<option value="' + newid + '">' + newname + '</option>\r';
}
newhtml += '\t\t\t</select>\r\t\t</li>\r';
// alert (thisid);
$('thisid').up('ul').insert (newhtml);
}
else {
alert (’ng');
newhtml = '<li>No good.</li>';
}
},
onFailure: function() {
alert ('Script failure.');
newhtml = '<li>No good.</li>';
}
});
// alert (newhtml);
// if (newhtml) {
// this.up('ul').insert (newhtml);
// }
}
Having established the variable thisid as this.id, I don't understand why $('thisid') doesn't work in the line $('thisid').up('ul').insert (newhtml); - especially as the value of thisid does show up correctly in the alert I've put in for testing (commented out). Why is this? If I put newhtml into that alert instead it's also correct.
And given that that seems not to work, I tried the alternative of passing the value of newhtml out (having declared it at the top) and inserting it in the page in the last block of code that's commented out - but that doesn’t work either.
Where am I going wrong?

How do I access every index of a specific Array inside an AJAX object

I'm calling an ajax for giphy, with this code:
$.ajax({
url: queryURL,
method: "GET"
}). then(function(response) {
console.log(response);
when I look at the console log there's an object with the first property being data. Each index of data is another object, inside this object are two properties i'm trying to pull, rating and url. I want to be able to list the rating and url not just of a specific index, but every index in that data array. What would be the best way to do that? Currently I've tried a for loop
for (var i = 0; i<response.data.length;i++){
var dataIndex = response.data[i];
}
then <creating a variable something like>
var imgURL = response.data[dataIndex].url
but its not working.
Here's the entire code
function displayTopicGif() {
var topic = $(this).attr("data-name");
// query url
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&limit=20&rating=r&api_key=";
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
// for loop to create a variable for the index of the objects data
for (var i = 0; i < response.data.length; i++) {
var dataIndex = response.data[i];
}
// where the gif's will be dumped
var topicDiv = $("<div class='topic'>");
// rating of gif
var rating = response.data[0].rating;
console.log(rating);
// Creating an element to have the rating displayed
var pOne = $("<p>").text("Rating: " + rating);
// add to the rating element
topicDiv.append(pOne);
// retrieve the IMG of the gif
var imgURL = response.data[0].url;
var image = $("<img>").attr("src", imgURL);
topicDiv.append(image);
// put gif into topic-view div
$("#topic-view").prepend(topicDiv);
});
}
You can check that something is an object using $.isPlainObject and then read through its properties via:
for (key in object) {
var value = object[key];
//log
}
Or you can get the keys using Object.getOwnPropertyNames();. See this sample excerpt from MDN:
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

Parse Cloud Code Save Issue

I wrote some backend code for a Parse.com mobile app a couple of years ago, and have just been asked to add a feature. However, I found that after a small tweak the code wouldn't succeed. So, I rolled back to the working copy, downloaded, then deployed that back and it wouldn't work either! I wonder if this is a change in the Parse software?
The code is failing at the save method as all the logs are fine until then. The log for the error case shows 'No message provided'. If I don't use the message attribute it just shows '{}', so I presume it's empty. I have put the promise resolution in the error case to stop the job timing out while I debug. One thing I have never understood is why I have to make two Seed objects and piggy-back off one to save correctly. If I did a.save(null,...) it wouldn't work.
Any help would be fantastic. Thanks!
PS: Apologies for the indenting below - it is correct in my file.
function flush() {
//Clear the previous records from the class.
var Seed = Parse.Object.extend("Seeds");
var _ = require("underscore");
var arr = [];
var query = new Parse.Query(Seed);
return query.find().then(function(oldSeeds) {
_.each(oldSeeds, function(oldSeed) {
arr.push(oldSeed.destroy());
});
return Parse.Promise.when(arr);
});
}
Parse.Cloud.job("fetchjson", function(request, status) {
var url = 'someurl';
flush().then(function() { Parse.Cloud.httpRequest({url: url}).then(function(httpResponse){
var Seed = Parse.Object.extend("Seeds");
var jsonobj = JSON.parse(httpResponse.text);
var _ = require("underscore");
var results = [];
// do NOT iterate arrays with `for... in loops`
_.each(jsonobj.seeds, function(s) {
var p = new Parse.Promise();
results.push(p); // Needs to be done here or when() will execute immediately with no promises.
var seed = new Seed();
var a = new Seed(s);
var image_url = a.get("image")
//Get the JSON.
Parse.Cloud.httpRequest({url: image_url}).then(function(response) {
console.log("Fetching image at URL: " + image_url);
//Create a new image object and save, passing ref through promise.
var file = new Parse.File('thumb.jpg', { base64: response.buffer.toString('base64', 0, response.buffer.length) });
return file.save();
}).then(function(thumb) {
console.log("Attaching thumb to object");
//Set image ref as object attribute.
a.set("imageFile", thumb);
console.log("Parsing views into viewsint");
//Save decimal string as int into another attribute.
a.set("viewsInt", parseInt(a.get("views")));
console.log("Parsing description into descriptionarray");
//Save string as array into another attribute.
var dar = new Array(1);
//dar[0] = a.get("description")
a.set("descriptionarray", [a.get("description")]);
}, function(error) {
console.log("Error occurred :(");
}).then(function(){
console.log("Saving object");
//Save the object and resolve the promise so we can stop.
seed.save(a,{
success: function(successData){
console.log(successData);
p.resolve(successData);
},
error: function(error){
console.log(error.message);
p.resolve(error);
}
});
});
});
// .when waits for all promises to be resolved. This is async baby!
Parse.Promise.when(results).then(function(data){
console.log("All objects saved");
status.success("Updated Succesfully");
});
}, function(error) {
//Oh noes :'(
console.error('Request failed with response code ' + httpResponse.status);
status.error("Update Failed");
});
});
});
I changed your code a bit and put some comments to explain:
// DEFINE THESE ON THE TOP. NO NEED TO REPEAT.
var _ = require("underscore");
var Seed = Parse.Object.extend("Seeds");
function flush() {
//Clear the previous records from the class.
var arr = [];
var query = new Parse.Query(Seed);
return query.find().then(function(oldSeeds) {
_.each(oldSeeds, function(oldSeed) {
arr.push(oldSeed.destroy());
});
return Parse.Promise.when(arr);
});
}
Parse.Cloud.job("fetchjson", function(request, status) {
var url = 'someurl';
flush().then(function() {
Parse.Cloud.httpRequest({url: url}).then(function(httpResponse){
var jsonobj = JSON.parse(httpResponse.text);
var results = [];
_.each(jsonobj.seeds, function(s) {
// ONE SEED OBJECT WITH INITIAL SET OF DATA FROM JSON
var seed = new Seed(s);
var image_url = seed.get("image")
// A SERIAL PROMISE FOR EACH SEED
var promise = Parse.Cloud.httpRequest({url: image_url}).then(function(response) {
console.log("Fetching image at URL: " + image_url);
//Create a new image object and save, passing ref through promise.
var file = new Parse.File('thumb.jpg', { base64: response.buffer.toString('base64', 0, response.buffer.length) });
return file.save();
}).then(function(thumb) {
// SETTING MORE PROPERTIES
//Set image ref as object attribute.
console.log("Attaching thumb to object");
seed.set("imageFile", thumb);
//Save decimal string as int into another attribute.
console.log("Parsing views into viewsint");
seed.set("viewsInt", parseInt(seed.get("views")));
//Save string as array into another attribute.
console.log("Parsing description into descriptionarray");
seed.set("descriptionarray", [seed.get("description")]);
// SAVING THE OBJECT
console.log("Saving object");
return seed.save();
});
// PUSH THIS PROMISE TO THE ARRAY TO PERFORM IN PARALLEL
results.push(promise);
});
Parse.Promise.when(results).then(function(data){
console.log("All objects saved");
status.success("Updated Succesfully");
});
}, function(error) {
console.error('Request failed with response code ' + httpResponse.status);
status.error("Update Failed");
});
});
});
Thanks knshn. I had refactored the code a lot since that version (including several of the changes you made), but I had posted the version that was identical to that which was working fine before. Your changes let me see the right error. For some reason doing the simple single object implementation didn't work for me originally, hence the nasty workaround. It works now though.
I have now found the culprit - the Seed class had an attribute called 'id'. With the old version this worked fine, but when I deployed that code now it gave an error 101: 'object not found for update'. This must be because the new Parse code is mixing that up with the internal objectId and getting confused that the id is different to what it expects. I wonder how that could still work with the rollback though. Perhaps the at version was tagged to use the older Parse code.
My fix was to use a different name for the id - 'seed_id'.

Post through google app scripts

I am trying to post from a HTML form to a Google sheet. I am currently just trying to write the code in the Google App script but an error states "Script function not found: doGet" and I cannot figure out what to do. My code is below:
function myFunction() {
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 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, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} 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());
}
}
Any help would be much appreciated.
You don't need to wrap the whole script in "myFunction()", if you remove that function with his corresponding bracket it should work just fine.
Remove this => function myFunction() { --from the beginning.
And this => } -- from the end.
You probably need to use ContentService
Google Documentation - Content Service

Resources