I am new to the world of * AppScript * I am currently designing a ** WepApp ** which is made up of html lists that connect to Mysql, when I individually test my lists paint correctly and their icons modify and update the data, without However ** the problem is ** when I join all my lists and call them through their corresponding url only the last one paints me the others are blank. For example of 10 lists I call # 2 the log tells me to call 10; I call 5 the same thing happens and if I call 10 it paints the data and they are allowed to be modified.
Within what I have searched I find that my problem lies in the way I render my pages but I cannot find the right path, so I ask for your support.
function doGet(e) {
var template ;
var view = e.parameters.v;
if(view == null){
template = HtmlService.createTemplateFromFile("Index");
}if(view == "Index"){
template = HtmlService.createTemplateFromFile("Index");
}if(view != null && view != "Index"){
template = HtmlService.createTemplateFromFile(view);
}
return template.evaluate()
.setTitle('Documental')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getTemplate(view){
return HtmlService.createTemplateFromFile(view);
}
and with this JavaScript method I connect my appscript code to pass it to my html
window.onload = function () {
google.script.run
.withSuccessHandler(run_This_On_Success)
.withFailureHandler(onFailure)
.readAreaPRE();
};
function onFailure(error) {
var div = document.getElementById("output");
div.innerHTML = "ERROR: " + error.message;
}
function run_This_On_Success (readAreaPRE) {
let table = $("#selectTable");
table.find("tbody tr").remove();
table.append("<tr><td>" + "</td><td>" + "</td></tr>");
readAreaPRE.forEach(function (e1, readAreaPRE) {
table.append(
"<tr><td>" +
e1[0] +
"</td><td>" +
e1[1] +
"</td><td>" +
"<p><a class='modal-trigger' id=" + e1[0] + " href='#modal1' onclick='capturaid("+e1[0]+",'"+ e1[1]+"')'><i class='material-icons'>edit</i></a>" +
"<a class='modal-trigger' href='#modal3' onclick='capturaidsup("+e1[0]+")'><i class='material-icons'>delete</i></a></p>" +
"</td></tr>"
);
});
};
function capturaidsup(dato1){
$("#delAreaPRE").val(dato1)
}
function capturaid(item1,item2) {
$("#uptAreaPRE1").val(item1);
$("#uptAreaPRE2").val(item2);
}
here is my function: readArePRE
function readAreaPRE() {
var conn = Jdbc.getCloudSqlConnection(url, user, contra);
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery(
"CALL `BD_CENDOC_COL`.`sp_lee_tb_ref_AreasPRE`()"
);
var numCols = results.getMetaData().getColumnCount();
var rowString = new Array(results.length);
var i = 0;
while (results.next()) {
var id_areaPRE = results.getInt("id_areaPRE");
var AreaPRE = results.getString("AreaPRE");
rowString[i] = new Array(numCols);
rowString[i][0] = id_areaPRE;
rowString[i][1] = AreaPRE;
i++;
}
return rowString;
conn.close();
results.close();
}
Thank you in advance, any correction to ask my question will be welcome.
Related
This question already has answers here:
Refresh data retrieved by a custom function in Google Sheet
(21 answers)
Closed 9 months ago.
I have ImportJson() function that doesn't update its value unless I make changes to Appscript then reload the sheet again, I think it was running but suddenly stopped.
The function should be get the value of 'A2' if found go to the loop, if not just return the fixed API call data, but whatever I update the A2 cell it doesn;t recall the function with the other kinds of the API call but it runs normally in the app script editor
function ImportData1() {
var Final_result = [];
var VenueId_results = [];
var PageNumber_index = 0;
var Page_number = [0, 1, 2, 3, 4];
var New_URL = "";
var url = "https://app.ticketmaster.com/discovery/v2/events?sort=venueName,asc&locale=*&size=199&" + "page=" + Page_number[PageNumber_index] + "&apikey=" + API_key + "&venueId=" + venueIds;
// ImportJSON(url, "/","noInherit,noTruncate,rawHeaders");
// console.log(ImportJSON(url, "/", "noInherit,noTruncate,rawHeaders"));
// console.log("Veuneid" + Veunue_id + Venue_Id_List.length);
console.log("ImportData1();" + Venue_Id_List.length);
var New_Venue = SpreadsheetApp.getActiveSheet().getRange('A2').getValue();
console.log(New_Venue);
if ( New_Venue != "") {
var Venue_arr = New_Venue.split(",");
VenueId_results = Add_new_VeunueId(Venue_arr);
var Last_New_Id_Venue = "";
for (var Index_venune = 2; Index_venune < (VenueId_results.length) - 2; Index_venune++) {
console.log("Venuesid " + VenueId_results[Index_venune]);
var New_Id_Venue = VenueId_results[Index_venune].toString() + ",";
Last_New_Id_Venue += New_Id_Venue;
console.log("New_Id_Venue " + New_Id_Venue);
}
console.log("Last_New_Id_Venue " + Last_New_Id_Venue);
New_URL = url + Last_New_Id_Venue;
New_Venue = "";
VenueId_results = [];
// return ImportJSON(New_URL, "/_embedded/events/name,/_embedded/events/url,/_embedded/events/_embedded/venues/name,/_embedded/events/dates/start/localDate,/_embedded/events/dates/start/dateTime,/_embedded/events/priceRanges/min,/_embedded/events/priceRanges/max,/_embedded/events/_embedded/venues/url,/_embedded/events/_embedded/venues/city/name", "noInherit,noTruncate,rawHeaders");
for (; PageNumber_index < Page_number.length; PageNumber_index++) {
console.log("looopsyes");
Final_result = Final_result.concat(ImportJSON(New_URL, "/_embedded/events/name,/_embedded/events/url,/_embedded/events/_embedded/venues/name,/_embedded/events/dates/start/localDate,/_embedded/events/dates/start/dateTime,/_embedded/events/priceRanges/min,/_embedded/events/priceRanges/max,/_embedded/events/_embedded/venues/url,/_embedded/events/_embedded/venues/city/name", "noInherit,noTruncate,rawHeaders"));
console.log("New_URL " + PageNumber_index + Page_number[PageNumber_index] + Final_result);
Utilities.sleep(1000);
}
console.log("New_URL " + New_URL);
console.log("Final_result " + Final_result);
return Final_result;
console.log("New_URL " + Page_number);
return Final_result;
// url += New_Venue;
var New_URL = url + New_Venue;
console.log("hello" + New_URL);
} else {
console.log("hellono");
New_Venue = "";
VenueId_results = [];
return ImportJSON(url, "/_embedded/events/name,/_embedded/events/url,/_embedded/events/_embedded/venues/name,/_embedded/events/dates/start/localDate,/_embedded/events/dates/start/dateTime,/_embedded/events/priceRanges/min,/_embedded/events/priceRanges/max,/_embedded/events/_embedded/venues/url,/_embedded/events/_embedded/venues/city/name", "noInherit,noTruncate,rawHeaders");
}
// /_embedded/events/name,/_embedded/events/url,/_embedded/events/dates/start/localDate,/_embedded/events/dates/start/dateTime,/_embedded/events/priceRanges/min,/_embedded/events/priceRanges/max,/_embedded/events/_embedded/venues/name,/_embedded/events/_embedded/venues/url,/_embedded/events/_embedded/venues/city/name
// setTimeout(import_data, 5000);
}
Here is a simple function that you can setup to trigger every time cell A2 changes. It will call your import function when the right cell has changed.
function valueChange(e)
{
if (e.range.getRow() == 1 && e.range.getColumn() == 2)
{
ImportData1();
}
}
I'm trying to send a telegram message to myself, every morning, with a different quote that I have listed in a Google Sheet. I wrote some code that adds messages to the list, but I can't seem to generate a random row from the list to send daily.
var token = "TOKEN";
var telegramAPI = "https://api.telegram.org/bot" + token;
var webAppAPI = "https://script.google.com/macros/s/GOOGLE_WEB_APP_ADDRESS";
var ssId = "SPREADSHEET_ID";
function getMe() {
var url = telegramAPI + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramAPI + "/setWebhook?url=" + webAppAPI;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramAPI + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Test Data" + JSON.stringify(e,null,4));
}
function doPost(e) {
Logger.log(e);
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var what = data.message.text.split("-")[0]
var who = data.message.text.split("-")[1]
var id = data.message.chat.id;
var name = data.message.chat.first_name;
var response = "Hi " + name + ", this quote has been added to your database: " + text;
sendText(id,response);
SpreadsheetApp.openById(ssId).getSheets()[1].appendRow([new Date(),id,name,text,response,what,who]);
All of this works fine. I added a query that pulls them over to my Quote sheet from my Telegram Feed sheet, that I'll put here to help someone:
=IFERROR(QUERY('Telegram Feed'!$G$1:$G$98,"",-1),"Error")
Now that I'm pulling in quotes, I want to generate a random one from the list and schedule it to send to myself on a daily basis. I've included what I've tried below, but I can't seem to figure out what I'm doing wrong.
The randomizer is partially working, but seems to be grabbing all of the content, which I need to refactor to say something along the lines of:
message = f"{quote} + ' - ' + {author}"
Randomizer:
function randomizer() {
var ssa = SpreadsheetApp.openById(ssId);
var ss = ssa.getSheetByName('Quotes');
var range = ss.getRange(1,1,ss.getLastRow(), 2);
var data = range.getValues();
for(var i = 0; i < data.length; i++)
{
var j = Math.floor(Math.random()*(data[i].length));
var element = data[i][j];
ss.getRange(i+1, 6).setValue(element);
Logger.log(element);
}
}
Up until this point, it mostly works (even though I need to figure out how to fix the randomizer function as mentioned above. It's when I try to send a random message from the script to Telegram that I run into problems.
function sendQuote(what,who) {
var data = randomizer();
var dataJSON = JSON.parse(data.postData.contents);
var url = telegramAPI + "/sendMessage?chat_id=" + 'CHAT_ID_NUM' + "&text=" + what + " - " who;
}
I'm getting nothing back. Anyone know what I'm doing wrong?
EDIT:
I followed the suggestions from Дмитро-Булах & carlesgg97, and I refactored a bunch of my randomize code to give me a quote and author. For some reason, I'm now getting the error "TypeError: Cannot read property "postData" from undefined.: from the line that reads var dataJSON = JSON.parse(data.postData.contents);
Does anyone know why this is happening?
I'll close the issue within 24hrs regardless. Thanks for the help everybody!
function sendQuote(quote,author) {
var data = randomize();
var dataJSON = JSON.parse(data.postData.contents);
var encodedText = encodeURIComponent(quote + " - " + author);
var url = telegramAPI + "/sendMessage?chat_id=" + 'CHAT_ID' + "&text=" + encodedText;
UrlFetchApp.fetch(url);
}
function randomize() {
var sss = SpreadsheetApp.openById(ssId);
var ss = sss.getSheetByName('Quotes');
var length = ss.getLastRow();
var overshoot = 97 //monitor for changes as list size increases
var true_length = length-overshoot;
var line = (Math.random() * ((true_length - 2) + 1)) + 2;
var quote_cell = ss.getRange(line,2);
var quote = quote_cell.getValue();
var author_cell = ss.getRange(line,1);
var author = author_cell.getValue();
Logger.log(quote + " - " + author);
}
Seems like you may be having two different problems:
You are not encoding the text as URL-safe. To safely append data (in this case the text URL Query string parameter) to your URL, you should use encodeURIComponent().
You don't seem to actually be sending the request. Did you miss the UrlFetchApp.fetch() call?
See below an example that fixes both issues:
function sendQuote(what,who) {
var data = randomizer();
var dataJSON = JSON.parse(data.postData.contents);
var encodedText = encodeURIComponent(what + " - " + who);
var url = telegramAPI + "/sendMessage?chat_id=" + 'CHAT_ID_NUM' + "&text=" + encodedText;
UrlFetchApp.fetch(url);
}
I'm experiencing some weird behavior in my code that I don't quite understand. I call a function, and inside that function there is another (anonymous) callback function it skips over and it goes to the end of the containing function, runs those lines, and then goes back into the callback function and runs those lines... Anybody have some insight, what am I doing wrong? Is it doing this because the "relatedQuery" method isn't complete yet so it hasn't hit the callback function before it runs the rest of the containing function's lines? That's the only thing I can think of, but I'm also not very skilled at JS. I've added some console.log statements that will tell you the order in which lines are being hit.
//Call the mgmtPopupContent function
mgmtTractPopupBox.setContent(mgmtPopupContent);
function mgmtPopupContent(feature) {
for (var attrb in feature.attributes) {
if (attrb == "HabitatManagement.DBO.MgmtTracts.OBJECTID") {
var OID = feature.attributes[attrb];
}
}
var relatedQuery = new RelationshipQuery();
relatedQuery.outFields = ["*"];
relatedQuery.relationshipId = 0;
relatedQuery.objectIds = [OID];
//Get data year that the map view is set to and set the definition expression on the table
viewYear = dom.byId("data-year").value;
relatedQuery.definitionExpression = "YearTreated = " + viewYear;
//Create table header that will go inside popup
var content = '<table id="mgmtPopupTable1"><tr><th>Veg Mgmt Practice</th><th>Herbicide</th><th>Month</th><th>Year</th>\
<th>Implemented By</th><th>Funded By</th><th>Farm Bill Code</th></tr>';
console.log("PRINTS FIRST");
//Do query and get the attributes of each related record for the popup
queryableMgmtTractFL.queryRelatedFeatures(relatedQuery, function (relatedRecords) {
console.log("PRINTS THIRD");
var fset = relatedRecords[OID].features;
fset.forEach(function (feature) {
var vegPractice = vegPName(feature.attributes.VegMgmtPractice);
var herbicide = herbName(feature.attributes.Herbicide);
var monthTreated = monthName(feature.attributes.MonthTreated);
var yearTreated = feature.attributes.YearTreated;
var impBy = impName(feature.attributes.ImplementedBy);
var fundBy = fundName(feature.attributes.FundedBy);
var fbc = feature.attributes.FarmBillCode;
if (fundBy == "CRP" || fundBy == "CRP - CREP") {
fbc = crpName(fbc);
}
else if (fundBy == "EQIP" || fundBy == "EQIP - RCPP") {
fbc = eqipName(fbc);
}
else {
fbc = "Not applicable";
}
row = '<tr><td>' + vegPractice + '</td><td>' + herbicide + '</td><td>' + monthTreated + '</td><td>' + yearTreated +
'</td><td>' + impBy + '</td><td>' + fundBy + '</td><td>' + fbc + '</td></tr>';
content = content + row;
});
content = content + '</table>';
});
console.log("PRINTS SECOND");
return content;
}
As mentioned in my comment, you have to wait for the queries to finish before you can render the content. So something like:
let content = '<table id="mgmtPopupTable1"><tr><th>Veg Mgmt Practice</th><th>Herbicide</th><th>Month</th><th>Year</th>\
<th>Implemented By</th><th>Funded By</th><th>Farm Bill Code</th></tr>';
const render_popup = function( content ) {
document.querySelector( '#myPopup' ).innerHTML = content;
};
// Render only the headers to begin with.
render_popup( content );
queryableMgmtTractFL.queryRelatedFeatures(relatedQuery, function (relatedRecords) {
var fset = relatedRecords[OID].features;
fset.forEach(function (feature) {
...
});
// Rerender the popup, now headers And content.
render_popup( content );
});
Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data
This code is for internal, offline, single user use, IE only. The code looks at a folder, and lists all files including those in subfolders. It sorts through the data based on some date fields and datelastmodified. It also uses and if to throw out thumbs.db entries. All of the data is put into a table.
My issue is that this script can take a long time to get the data. I would like to add a progress bar but the progress bar cant update while the script is running. After some research it looks like SetTimeOut can allow the page elements to be updated as the script runs, therefore allowing the progress bar to work and looking overall cleaner. However I can not figure out of to implement SetTimeOut into my existing code.
<script type="text/javascript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
function ShowFolderFileList(folderspec) {
var beginningdate = new Date(startdate.value);
var finishdate = new Date(enddate.value);
var s = "";
var f = fso.GetFolder(folderspec);
var subfolders = new Enumerator(f.SubFolders);
for (subfolders.moveFirst(); !subfolders.atEnd(); subfolders.moveNext()) {
s += ShowFolderFileList(subfolders.item().path);
}
// display all file path names.
var fc = new Enumerator(f.files);
for (i = 0; !fc.atEnd(); fc.moveNext()) {
if (fc.item().name != "Thumbs.db") {
var dateModified = fc.item().DatelastModified;
if (dateModified >= beginningdate && dateModified <= finishdate) {
Date.prototype.toDateString = function () {
return [this.getMonth() + 1, '/', this.getDate(), '/', this.getFullYear()].join('');
}
var dateModifiedClean = (new Date(fc.item().DatelastModified).toDateString());
s += "<table border=0 width=100% cellspacing=0><tr " + ((i % 2) ? "" : "bgcolor=#EBF1DE") + "><td width=75%><font class=find><b>" + fc.item().ParentFolder.name + "</b>" + " - " + fc.item().name + "</font></td><td width=25% align=right><font class=find>" + dateModifiedClean + "</font></td></tr>";
i++;
}
}
}
var results = s + "</table>";
return results;
}
function listFiles() {
outPut.innerHTML = ShowFolderFileList('*Path to scan*');
}
</script>
outPut is the ID of a div tag where the results table is displayed. A button calls the listfiles function.