How to get the value of two nodes in Firebase? - javascript

I use firebase doc as reference to do the following code. I try other combinations with no success. There is no security access to database.
So, How can this code read or get value of two nodes at the same time?
function gofb(d) {
var r = d.getAttribute("data-id");
var p1name, p2name, pa1, pa2, pb1, pb2;
return firebase.database().ref('/wc2017/' + r + '/t1').once('value').then(
function(snapshot) {
pa1 = snapshot.val().pd1;
pa2 = snapshot.val().pd2;
p1name = pa1 + "|" + pa2;
});
return firebase.database().ref('/wc2017/' + r + '/t2').once('value').then(
function(snapshot) {
pb1 = snapshot.val().pd1;
pb2 = snapshot.val().pd2;
p2name = pb1 + "|" + pb2;
});
return firebase.database().ref('/wc2017/' + r).update({
a0_start: firebase.database.ServerValue.TIMESTAMP});
console.log(t1name);
console.log(t2name);
}

You can simply get the snapshot for the parent object's value. And get the values you want. Please refer to the following code.
firebase.database().ref('/wc2017/' + r).once('value',function(snapshot){
sValue = snapshot.val();
pa1t1 = sValue.t1.pd1;
pa2t1 = sValue.t1.pd2;
pb1t2 = sValue.t2.pd1;
pb2t2 = sValue.t2.pd2;
});

Related

How to render multiple html lists with AppScrip?

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.

Sending message to Telegram from Google Sheet via Google Scripts

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);
}

Issues attempting to display data from JSON file

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

I need my code to get the values before the commas but it only grabs one of them - Javascript

I am fairly new to the Javascript language.
I am trying to make a clicker game (not so hard). The game is working but I am trying to make a save method for the game.
Instead of cookies I decided to have the game make its own code where the user can copy and paste it the next time they get on the game.
So the save method works but when I try to have the game load the code it doesn't quite do it right.
Instead of grabbing the values before the commas it grabs the letters of the word I use as a checker.
Is there a way I can fix this?
Here's my code:
var shovel = 0;
var miner = 0;
var loaders = 0;
var drill = 0;
var tnt = 0;
var minecart = 0;
var bulldozer = 0;
var trucks = 0;
var manager = 0;
var cost1 = 10;
var cost2 = 200;
var cost3 = 350;
var cost4 = 500;
var cost5 = 600;
var cost6 = 800;
var cost7 = 2500;
var cost8 = 6000;
var cost9 = 100000;
var cash = 0;
var cashRate = 1000;
//-- SAVE GAME --
function save() {
var save = "";
var data = cash + "," + cashRate + "," + shovel + "," + miner + "," + loaders + "," + drill + "," + tnt + "," + minecart + "," + bulldozer + "," + trucks + "," + manager + "," + cost1 + "," + cost2 + "," + cost3 + "," + cost4 + "," + cost5 + "," + cost6 + "," + cost7 + "," + cost8 + "," + cost9;
save += "CoalMinerGame=" + data;
var finalSave = encode(save);//Encoding/Decoding is done using the Base64 Code
prompt("Keep this somewhere you'll remember!", finalSave);
}
function load() {
var code = prompt("Paste the save code below!", "");
if (code != "") {
var load = decode(code);
if (load.includes("CoalMinerGame=")) {
load.split("CoalMinerGame=");
//load[0] = blank
cash = load[1];
cashRate = load[2];
shovel = load[3];
miner = load[4];
loaders = load[5];
drill = load[6];
tnt = load[7];
minecart = load[8];
bulldozer = load[9];
trucks = load[10];
manager = load[11];
cost1 = load[12];
cost2 = load[13];
cost3 = load[14];
cost4 = load[15];
cost5 = load[16];
cost6 = load[17];
cost7 = load[18];
cost8 = load[19];
cost9 = load[20];
updateWorkers();
alert("Save Successfully Loaded!");
} else {
alert("Not a valid save code!");
}
} else {
alert("You must enter a save code to get your game back!");
}
}
Save
Load
I see two mistakes :
The load.split() function does not modify load but returns an array instead, an array that you should store in another variable.
You should also split once again the resulting string on commas to separate your different values.
Hope it helps!
Oh man, this code is giving me a pain :).
What about use some native functions for whole objects so you dont have to manually serialize it and deserialize it?
This code
const myObject = {
some: 'fields',
even: {
nested: 'fields',
},
};
const stringified = JSON.stringify(myObject);
console.log(stringified);
const unstringified = JSON.parse(stringified);
console.log(unstringified);
Is having this output
{"some":"fields","even":{"nested":"fields"}}
{ some: 'fields', even: { nested: 'fields' } }
You can also use base64 steps to code and decode
The JSON.stringify take JS object and create pure string which contains JSON inside.
Then when you want to take JSON and create object from it, you can just JSON.Parse, which expects string.
I echo the sentiment to use JSON. My example below might require some refactoring in the game code but would be cleaner. To access the variable cash you would just use gameData.cash where you currently are using the cash var.
var gameData = {
cash: 0,
cashRate:0,
shovel:0,
miner:0,
loaders:0,
drill:0,
tnt:0,
minecart:0,
bulldozer:0,
trucks:0,
manager:0,
cost1:10,
cost2:200,
cost3:350,
cost4:500,
cost5:600,
cost6:800,
cost7:2500,
cost8:6000,
cost9:100000
}
function save(){
var dataToSave = CoalMinerGame: {
cash: cash,
cashRate:cashRate,
shovel:shovel,
miner:miner,
loaders:loaders,
drill:drill,
tnt:tnt,
minecart:minecart,
bulldozer:bulldozer,
trucks:trucks,
manager:manager,
cost1:cost1,
cost2:cost2,
cost3:cost3,
cost4:cost4,
cost5:cost5,
cost6:cost6,
cost7:cost7,
cost8:cost8,
cost9:cost9
}
var finalSave = JSON.Stringify(dataToSave)
finalSave = encode(finalSave)
prompt("Keep this somwhere you'll remember!", finalSave)
}
function load(){
var code = prompt("Paste the save code below!", "")
var load = decode(code)
if (code != ""){
gameData = load;
updateWorkers();
alert("Save Successfully loaded!")
} else {
alert("You must enter a save code to get your game back!")
}
}

how to run javascript object from string without using eval()

i have a json object that has item type and id, i need to create new object
var data = {
"items":[
{"type":"generator","id":"item_1","x":200,"y":200},
{"type":"battery","id":"item_2","x":50,"y":300},
{"type":"generator","id":"item_3","x":200,"y":280},
{"type":"battery","id":"item_4","x":100,"y":400}
]
};
and i need to run for each item in items
jQuery.each(data.items, function(index,value) {
eval("var " + value.id + " = new " + value.type + "(" + (index + 1) + ");");
eval(value.id + ".id = '" + value.id + "';");
eval(value.id + ".draw(" + value.x + "," + value.y + ");")
});
this is not a good practice, but what else can i do?
i need then to have the control on the items
something like
item_1.moveto(300,700);
but i always get item_1 is undefind
You can create a factory method which allows to generate concrete types out of an abstract data structure:
var createItem = (function () {
var types = {};
function createItem(index, data) {
data = data || {};
var ctor = types[data.type], item;
if (!ctor) throw new Error("'" + data.type + "' is not a registered item type.");
item = new ctor(index);
item.id = data.id;
return item;
}
createItem.registerType = function (type, ctor) {
types[type] = ctor;
};
return createItem;
})();
Then register item types to the factory:
function Generator(index) {/*...*/}
createItem.registerType('generator', Generator);
And finally create an object map to lookup your items by id (you could use a specialized object like ItemsMap instead of a plain object), loop through your items and add them to the map.
var itemsMap = {};
data.items.forEach(function (itemData, i) {
var item = itemsMap[itemData.id] = createItem(i + 1, itemData);
//you can also draw them at this point
item.draw(itemData.x, itemData.y);
});
You can now lookup objects by id like:
var item1 = itemsMap['item_1'];
var objects = {};
objects[value.id] = new window[value.type](index + 1);

Categories

Resources