Modifying script for Google sheets - javascript

To log sensor data to Google sheets using ESP32, I found a script online to accomplish that. However, I want to modify it so that I could have additional data fields logged. I don't know much about JavaScript but tried to add a new var and modify the code but it doesn't work. Here is the original script:
function doGet(e){
Logger.log("--- doGet ---");
var tag = "",
value = "";
try {
// this helps during debuggin
if (e == null){e={}; e.parameters = {tag:"test",value:"-1"};}
tag = e.parameters.tag;
value = e.parameters.value;
// save the data to spreadsheet
save_data(tag, value);
return ContentService.createTextOutput("Wrote:\n tag: " + tag + "\n value: " + value);
} catch(error) {
Logger.log(error);
return ContentService.createTextOutput("oops...." + error.message
+ "\n" + new Date()
+ "\ntag: " + tag +
+ "\nvalue: " + value);
}
}
// Method to save given data to a sheet
function save_data(tag, value){
Logger.log("--- save_data ---");
try {
var dateTime = new Date();
// Paste the URL of the Google Sheets starting from https thru /edit
// For e.g.: https://docs.google.com/..../edit
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1-3NY0nbnJgx_RHJeG6GckfVesUXBI5rgxmTJ40yX0vE/edit");
var dataLoggerSheet = ss.getSheetByName("Datalogger");
// Get last edited row from DataLogger sheet
var row = dataLoggerSheet.getLastRow() + 1;
// Start Populating the data
dataLoggerSheet.getRange("A" + row).setValue(row -1); // ID
dataLoggerSheet.getRange("B" + row).setValue(dateTime); // dateTime
dataLoggerSheet.getRange("C" + row).setValue(tag); // tag
dataLoggerSheet.getRange("D" + row).setValue(value); // value
// Update summary sheet
summarySheet.getRange("B1").setValue(dateTime); // Last modified date
// summarySheet.getRange("B2").setValue(row - 1); // Count
}
catch(error) {
Logger.log(JSON.stringify(error));
}
Logger.log("--- save_data end---");
}
Here is the version with my additions:
function doGet(e){
Logger.log("--- doGet ---");
var tag = "",
value = "",
tag2 = "",
val2 = "";
try {
// this helps during debuggin
if (e == null){e={}; e.parameters = {tag:"test",value:"-1", tag2: "test2", val2: "-1"};}
tag = e.parameters.tag;
value = e.parameters.value;
tag2 = e.parameters.tag2;
val2 = e.parameters.val2;
// save the data to spreadsheet
save_data(tag, value, tag2, val2);
return ContentService.createTextOutput("Wrote:\n tag: " + tag + "\n value: " + value + "\n tag2: " + tag2 + "\n val2: " + val2);
} catch(error) {
Logger.log(error);
return ContentService.createTextOutput("oops...." + error.message
+ "\n" + new Date()
+ "\ntag: " + tag
+ "\nvalue: " + value
+ "\n tag2: " + tag2
+ "\n val2: " + val2);
}
}
// Method to save given data to a sheet
function save_data(tag, value, tag2, val2){
Logger.log("--- save_data ---");
try {
var dateTime = new Date();
// Paste the URL of the Google Sheets starting from https thru /edit
// For e.g.: https://docs.google.com/..../edit
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1-3NY0nbnJgx_RHJeG6GckfVesUXBI5rgxmTJ40yX0vE/edit");
var dataLoggerSheet = ss.getSheetByName("sht31_1");
// Get last edited row from DataLogger sheet
var row = dataLoggerSheet.getLastRow() + 1;
// Start Populating the data
dataLoggerSheet.getRange("A" + row).setValue(row -1); // ID
dataLoggerSheet.getRange("B" + row).setValue(dateTime); // dateTime
dataLoggerSheet.getRange("C" + row).setValue(tag); // tag
dataLoggerSheet.getRange("D" + row).setValue(val); // value
dataLoggerSheet.getRange("E" + row).setValue(tag2); // tag
dataLoggerSheet.getRange("F" + row).setValue(val2); // value
// Update summary sheet
summarySheet.getRange("B1").setValue(dateTime); // Last modified date
// summarySheet.getRange("B2").setValue(row - 1); // Count
}
catch(error) {
Logger.log(JSON.stringify(error));
}
Logger.log("--- save_data end---");
}
So when I send the data using a GET request, only values of original variables (tag and value) are posted to the google sheet. Could you please tell how can I fix it?
EDIT: I have tried making a GET request manually using Postman to test if the script works. Here is the request:
https://script.google.com/macros/s/AKfycbwibc1auwDUtlRPIkIpO53FM6DivTLLNscMjBPGOaeajcVkZb6i7LH6gwp2Lw8I174B/exec?tag=Temp&value=21.13&tag2=Humid&val2=47.87

Related

Resolve 'Parsing Error: Please check your selector. (line XX)' Javascript/AWQL

First off, let me say that I am not a developer, nor do I really code beyond basic HTML. So I appreciate your patience. :)
I'm working with a script that is for AdWords, but I believe it's more or less written in Javascript. (I've included the script below.)
Basically, I'm receiving the error message 'Parsing Error: Please check your selector. (line XX)' when I preview the script.
I've searched all around for hours and have yet to find a solution.
I think it may be that a query being returned contains either a single or double quote, and may be messing up the code? Though I can't actually prove that.
Also, yes, I was sure to update lines 17-21 with the correct details.
Any help would be much appreciated!
Thanks!
John
/*
// AdWords Script: Put Data From AdWords Report In Google Sheets
// --------------------------------------------------------------
// Copyright 2017 Optmyzr Inc., All Rights Reserved
//
// This script takes a Google spreadsheet as input. Based on the column headers, data filters, and date range specified
// on this sheet, it will generate different reports.
//
// The goal is to let users create custom automatic reports with AdWords data that they can then include in an automated reporting
// tool like the one offered by Optmyzr.
//
//
// For more PPC management tools, visit www.optmyzr.com
//
*/
var DEBUG = 0; // set to 1 to get more details about what the script does while it runs; default = 0
var REPORT_SHEET_NAME = "report"; // the name of the tab where the report data should go
var SETTINGS_SHEET_NAME = "settings"; // the name of the tab where the filters and date range are specified
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1dttJTb547L81XYKdTQ56LcfO9hHhbb9wm06ZY5mKhEo/edit#gid=0"; // The URL to the Google spreadsheet with your report template
var EMAIL_ADDRESSES = "example#example.com"; // Get notified by email at this address when a new report is ready
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query); //THIS IS LINE 103 WITH THE ERROR
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = "currentSetting.ss<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
The area between SELECT and FROM is the selector. You're not selecting any fields with that query. That's happening because the headerNames array is empty. Verify the value of REPORT_SHEET_NAME

SharePoint working with lookup dropdowns and getting values

I seem to have a little trouble getting a value to be returned from a dropdown lookup field. I've got the following code that gets me the values from the list I'm doing the lookup upon:
var siteUrl = _spPageContextInfo.webServerRelativeUrl;
function getDropdownValues(tempNumTitle) {
var clientContext = new SP.ClientContext(siteUrl);
var tempDropdownValueList = clientContext.get_web().get_lists().getByTitle('Temps');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View>' +
'<RowLimit>' +
'100' +
'</RowLimit>' +
'</View>');
this.tempQuery = tempDropdownValueList.getItems(camlQuery);
clientContext.load(tempQuery);
clientContext.executeQueryAsync(
// on success of getting Temp Values from dropdown
// match it with the tempNum entry
function (sender, args) {
var tempDropDownValues = {};
var tempEnumerator = tempQuery.getEnumerator();
while(tempEnumerator.moveNext()) {
var tempItem = tempEnumerator.get_current();
var tempTitle = tempItem.get_item('Title');
var tempId = tempItem.get_item('ID');
tempDropDownValues[tempTitle] = tempId;
}
selectTemp(tempNumTitle, tempDropdownValues)
},
// on failure
function (sender, args) {
console.info('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);
}
It performs this fine, giving me the dropdown values. It then calls the function selectTemp with the parameters of the tempNumTitle we are looking for, and the list of dropdown values retrieved. Here is the next function:
function selectTemp(tempNumTitle, tempValues) {
var clientContext = new SP.ClientContext(siteUrl);
var tempMatchValueList = clientContext.get_web().get_lists().getByTitle('Numbers-Temp');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View>' +
'<Query>' +
'<Where>' +
'<Eq>' +
'<FieldRef Name="Title" />' +
'<Value Type="Text">' + tempNumTitle + '</Value>' +
'</Eq>' +
'</Where>' +
'</Query>' +
'</View>');
this.tempMatchValueQuery = tempMatchValueList.getItems(camlQuery);
clientContext.load(tempMatchValueQuery);
clientContext.executeQueryAsync(
// on success
function (sender, args) {
var temp = '';
tempEnumerator = tempMatchValueQuery.getEnumerator();
while(tempEnumerator.moveNext()) {
var tempItem = tempEnumerator.get_current();
temp = tempItem.get_item('Temp0');
}
},
// on failure
function (sender, args) {
console.info('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);
}
It almost gets me what I'm looking for, but I get something like this:
temp: {$1E_1: 3, $2e_1: "Temp 3"}
Where I want the value of the $2e_1, or "Temp 3". How can I get that value, without just going temp["$2e_1"]?
When accessing a lookup column or a people picker column, the column value is a complex type rather than a simple string.
You can invoke .get_lookupValue() on the returned object to get a text representation of the lookup column's value, or .get_lookupId() to get the ID number of the corresponding item in the lookup list (or in the site collection's user information list in the case of a people picker column).
So in your case, assuming "Temp0" is the internal name of a lookup column, you should be able to do this:
temp = tempItem.get_item('Temp0').get_lookupValue();

HTML read javascript and put result into a div

I'm new to HTML/javascript and I want to make something that displays Last.FM current playing songs, into a div on html, which displays it in text, I have a code that sends the current song through a chat on www.irccloud.com, and I was wondering If you could change it so that It could get received and put into a DIV on a page, the code is below:
and var r is the completed code, so how would I do something in the div that picks up the source as the link above and then grabs var r from it? If so, how would I do it??
I have tried the following code here
Sorry if I do not make sense.
(function () {
var e = "DeviousRunner";
window.lfmRecentTrack = function (t) {
var n = (new Array).concat(t.recenttracks.track)[0];
var album, spurl;
if (n.album["#text"]) {
album = " (from " + n.album["#text"] + ")";
} else {
album = "";
}
try {
var spotify = new XMLHttpRequest();
spotify.open("GET", "https://ws.spotify.com/search/1/track.json?q=" + encodeURIComponent(n.artist["#text"] + " - " + n.name), false);
spotify.send();
var spotresp = JSON.parse(spotify.responseText);
if (spotresp["tracks"].length > 0) {
//var urisplit = spotresp["tracks"][0]["href"].split(":");
//spurl = " https://open.spotify.com/" + urisplit[1] + "/" + urisplit[2];
spurl = spotresp["tracks"][0]["href"];
} else {
console.log("spotify: couldn't get url");
spurl = "";
}
} catch(e) {
console.log("spotify: " + e.message);
spurl = "";
}
var r = "is listening to " + n.name + " by " + n.artist["#text"] + " " + album + " (" + spurl + ")";
}
var n = document.createElement("script");
n.setAttribute("type", "text/javascript");
n.setAttribute("src", "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + e + "&api_key=dd5fb083b94a7196cf696b9d7d11bc63&limit=1&format=json&callback=window.lfmRecentTrack");
document.body.appendChild(n)
})();
I updated your FIDDLE,
by moving this:
var element = document.getElementById("rss");
element.innerHTML = r;
inside the function...
hope this is useful for you

JScript try catch network exception

I'm writing a script that stores database backup files to multiple locations. In addition, the data is stored on a NAS, which is normally accessible. If this is not the case, the error message is to be intercepted.
I tried it this way:
wshshell = WScript.CreateObject("WScript.Shell");
fso = WScript.CreateObject("Scripting.FileSystemObject");
SetupPath = WScript.arguments(0);
if (fso.FileExists(SetupPath))
{
//Load setup JSON
SetupFile = fso.OpenTextFile(SetupPath, 1, true, 0);
eval(SetupFile.ReadAll());
// Parse setup configuration from JSON
...
BackupPath = Setup["BackupPath"];
FilesForBackup = Setup["FilesForBackup"];
NASBackupPath = Setup["NASBackupPath"];
...
CreateNewBackupFiles();
Log("Script was successfully executed.");
}
else
{
Log("Script was not successfully executed.");
}
/* Creates a new compressed database backup */
function CreateNewBackupFiles()
{
tempfile = fso.GetTempName();
file = fso.GetFile("C:\\Program\\7-Zip\\7z.exe");
rarexe = file.ShortPath;
script = rarexe + " a -r " + tempfile + " " + FilesForBackup;
wshshell.Run(script, 0, true);
fso.CopyFile(tempfile, BackupPath + PrefixBackupFile + "backup.7z");
//Save to NAS
if(NASBackupPath!="")
{
try
{
fso.CopyFile(tempfile, NASBackupPath);
}
catch(err)
{
Log("Path \"" + NASBackupPath + "\" not available.");
}
}
fso.DeleteFile(tempfile, true); //delete tempfile
}
/* Saves a log in "Debug.Log" */
function Log(msg)
{
fs = WScript.CreateObject("Scripting.FileSystemObject");
a = fs.OpenTextFile("Debug.log", 8, true, 0);
line = "[" + CurrentTime()+ "] ";
line += "[" + WScript.ScriptName + "] ";
line += "[" + msg + "]";
a.WriteLine(line);
}
Nevertheless, errors continue to be issued. I´m using the Script on Windows XP SP3. Is there a possibility to catch this error with javascript?
thanks
I have found the error. The error came from the "Log". First, not every time a new "File System object" must be created. It can be simply used the object "fso". In addition, the open text file must be closed at the end of the function. Here is the correction:
function Log(msg)
{
a = fso.OpenTextFile("Debug.log", 8, true, 0);
line = "[" + CurrentTime()+ "] ";
line += "[" + WScript.ScriptName + "] ";
line += "[" + msg + "]";
a.WriteLine(line);
a.Close();
}

Why I always get "Uncaught SyntaxError: Unexpected token u " from Chrome?

I have spent a whole day on this, googling and searching for answers but still could not figure out.
My code is a bit long and it works well in Firefox but gets "Uncaught SyntaxError: Unexpected token u " from Chrome.
Can anyone points me out where I am wrong? Thanks in advance!
// when the page loads, list all the current contacts
$(document).ready(function(){
// check if localStorage database exists
if(!localStorage.getItem("customerDatabase")){
// define a JSON object to hold all current address
var contacts = {
"users":[
{
"id":"1",
"name":"dennis",
"email":"dennisboys#gmail.com"
},
{
"id":"2",
"name":"zoe",
"email":"zoeisfemale#gmail.com"
}
]
} // end of contacts JSON object
// stringify the object
var stringObject = JSON.stringify(contacts);
// store it into localStorage database
var storedDatabase = localStorage.setItem("customerDatabase", stringObject);
} else {
// list all customers upon page loads
listJSONCustomers();
}
// list all current contacts from JSON object in localStorage
function listJSONCustomers(){
var displayHTML = "";
var i;
// get the data from localStorage
var storedDatabase = localStorage.getItem("customerDatabase");
// parse the data from string to JSON object
var parseObject = JSON.parse(storedDatabase);
// access the users key of the JSON object
var userObject = parseObject.users;
// get the length of the object (how many customers the database has)
var contactsLength = userObject.length;
for(i=0; i<contactsLength; i++){
var trElement = '<tr id="address' + (i+1) + '">';
var tdId = '<td id="id' + (i+1) + '">' + userObject[i].id + '</td>';
var tdName = '<td id="name' + (i+1) + '">' + userObject[i].name + '</td>';
var tdEmail = '<td id="email' + (i+1) + '">' + userObject[i].email + '</td>';
var tdButton = '<td id="button"><button id="editButton' + userObject[i].id + '">Edit</button> | <button id="deleteButton' + userObject[i].id + '">Delete</button></td>';
displayHTML += trElement + tdId + tdName + tdEmail + tdButton + '</tr>';
}
$('#address_list').html(displayHTML);
}
// add customer to database
$('#saveCustomer').click(function(){
if( $('#customerName').val() !== "" && $('#customerEmail').val() !== "" ){
var customerName = $('#customerName').val();
var customerEmail = $('#customerEmail').val();
// get the data from localStorage
var storedDatabase = localStorage.getItem("customerDatabase");
// parse the data from string to JSON object
var parseObject = JSON.parse(storedDatabase);
// access the users key of the JSON object
var userObject = parseObject.users;
// get the new entry
var newCustomerObject = {
"id": userObject.length + 1,
"name": customerName,
"email": customerEmail
};
// push the new entry into the object
userObject.push(newCustomerObject);
// convert the object into string for localStorage
var stringObject = JSON.stringify(parseObject);
// store the JSON object into localStorage
var storedDatabase = localStorage.setItem("customerDatabase", stringObject);
// list all customes again every time a database receives a new entry
listJSONCustomers();
} else {
alert("Please enter customer's name and email.");
}
}); // end of $('#saveCustomer').click();
});
At some point, something you did corrupted the value of your LocalStorage for that key. LocalStorage can only store strings, so if you pass anything else to it, it will convert it to a string. Since your value is 'undefined', that means that at some point, you probably did something like this on accident:
var value;
localStorage.setItem('key', value);
In this case, value is undefined, which is not a string. When this gets saved, it will be converted however. Unfortunately, "undefined" is not valid JSON. That means that when it tries to parse, it will throw an exception.
To fix your issue, you should clear the bad value out with removeItem.
localStorage.removeItem("customerDatabase");

Categories

Resources