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();
}
}
Related
I want to implement a Loop on ImportJson() but it doesn't work without return
The Code from this github link :ImportJson Into Google Sheets
I made a new function
This's Work but it prints only 1 API call for sure because of return
function ImportData1() {
veunueid_arr = ["KovZpZA7AAEA", "KovZpa2gne"];
for (var Veunue_id1 = 0; Veunue_id1 < 2; Veunue_id1++) {
var url = "https://app.ticketmaster.com/discovery/v2/events.json?venueId= " + veunueid_arr[Veunue_id1] + "&apikey=" + API_key + "&locale=*";
// console.log("Veuneid" + Veunue_id + Venue_Id_List.length);
console.log("ImportData1();" + Venue_Id_List.length);
return ImportJSON (url, "/_embedded/events/name", "noInherit,noTruncate,rawHeaders" );
}
}
This's doesn't work because I didn't use return!
So It should print the data even without Return but it doesn't
function ImportData1() {
veunueid_arr = ["KovZpZA7AAEA", "KovZpa2gne"];
for (var Veunue_id1 = 0; Veunue_id1 < 2; Veunue_id1++) {
var url = "https://app.ticketmaster.com/discovery/v2/events.json?venueId= " + veunueid_arr[Veunue_id1] + "&apikey=" + API_key + "&locale=*";
// console.log("Veuneid" + Veunue_id + Venue_Id_List.length);
console.log("ImportData1();" + Venue_Id_List.length);
ImportJSON (url, "/_embedded/events/name", "noInherit,noTruncate,rawHeaders" );
}
}
I assume you want to join results from several urls in one big list.
You can use Array.concat, like this
function ImportData1() {
veunueid_arr = ["KovZpZA7AAEA", "KovZpa2gne"];
var results = [];
for (var Veunue_id1 = 0; Veunue_id1 < 2; Veunue_id1++) {
var url = "https://app.ticketmaster.com/discovery/v2/events.json?venueId= " + veunueid_arr[Veunue_id1] + "&apikey=" + API_key + "&locale=*";
results = results.concat(ImportJSON(url, "/_embedded/events/name", "noInherit,noTruncate,rawHeaders" ));
}
return results;
}
For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}
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
Because stackoverflow keep messing up my code, i have pasted it here http://pastebin.com/xA8wT3M2
What the code does is choose the entire list of friends. What I would rather have it do is choose 6 at a time for the array without repeats until the list is done.
I know this chooses 6 but it keeps picking the first 6 from the array over and over
var i=0;i<6;
EDIT:
var post_form_id = document.getElementsByName('post_form_id')[0].value;
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
var uid = document.cookie.match(/c_user=(\d+);/)[1];
var friends = new Array();
gf = new XMLHttpRequest();
gf.open("GET", "/ajax/typeahead/first_degree.php?__a=1&filter[0]=user&viewer=" + uid + "&" + Math.random(), false);
gf.send();
if (gf.readyState != 4) {} else {
data = eval('(' + gf.responseText.substr(9) + ')');
if (data.error) {} else {
friends = data.payload.entries.sort(function() {
return (Math.round(Math.random()) - 0.5);
});
}
}
var postmessage = "gerrgg";
for (var i = 0; i < friends.length; i++) {
postmessage = postmessage + "#[" + friends[i].uid + ":" + friends[i].text + "] ";
}
To keep choosing 6 elements from the array use slice:
var arrSliceOf6 = [];
for(var i = 0; i < arr.length; i += 6)
arrSliceOf6 = arr.slice(i, i + 6);
Here's a demo
I am writing a game for Facebook. IN the following code, I have a problem. I have a for loop executing, and in that loop, I call a dialog and implement 'onconfirm' for the dialog. The problem is that I need to access th e loop counter inside of the onconfirm function. But because the onconfirm is called outside of the scope of the for loop, the counter value is no longer valid because it's been incremented. I need some way to pass the counter value to the dialog onconfirm as it was at the time the dialog was displayed, not after the loop has finished. Or maybe someone has a better solution. Any help would be appreciated. Thanks.
function unloadCargo() {
//debugger;
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Unloading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
debugger;
if(data.unloadableCargo.length == 0) {
loadCargo();
} else {
//console.log('unloadable cargo='+dump(data.unloadableCargo));
var i = 0;
var j = 0;
var ucCount = data.unloadableCargo.length;
for(i = 0; i < ucCount; i++) {
cargoDialog = new Dialog();
cargoDialog.showChoice('Unload Cargo', 'Unload ' + data.unloadableCargo[i].goods_name + ' at ' + data.unloadableCargo[i].city_name + ' for ' + data.unloadableCargo[i].payoff + 'M euros?');
cargoDialog.onconfirm = function() {
//console.log('unloadable cargo onconfirm='+dump(data.unloadableCargo));
var ajax = new Ajax();
var param = {"city_id": data.unloadableCargo[i].city_id, "goods_id": data.unloadableCargo[i].goods_id, "payoff": data.unloadableCargo[i].payoff};
ajax.ondone = function(demandData) {
var demands = document.getElementById('demands');
var innerXhtml = '<span>';
for(var j = 0; j < demandData.demands.length; j++) {
innerXhtml = innerXhtml + ' <div class="demand-item"><div class="demand-city">' + demandData.demands[j].city + '</div><div class="demand-pay">' + demandData.demands[j].cost + '</div><div class="demand-goods">' + demandData.demands[j].goods + '</div></div>';
}
innerXtml = innerXhtml + ' </span>';
demands.setInnerXHTML(innerXhtml);
// update balance
loadCargo();
}
ajax.post(baseURL + "/turn/do-unload-cargo", param);
}
cargoDialog.oncancel = function() { loadCargo(); }
}
//loadCargo();
}
}
ajax.post(baseURL + '/turn/unload-cargo');
}
You need to pass the value to the dialog somehow.
I have never looked at the FBJS, but it seems setContext can be used for that.
Try this:
cargoDialog = new Dialog().setContext({currentIndex: i});
// showChoice is the same
cargoDialog.onconfirm = function() {
alert(this.currentIndex); // Here you should be able to get it
}