How to retreive data from Firebase with JavaScript - javascript

I am trying to retrieve some data from Firebase using JavaScript, but I have a problem. I can't get the items of my child "Usuarios".
This is how my database looks like
var rootRef = firebase.database().ref().child("Usuarios");
rootRef.on("child_added", snap => {
var name = snap.child("Nombre").val();
var email `enter code here`= snap.child("Apellido").val();
$("#table_body").append("<tr><td>" + name + "</td><td>" + email + "</td><td><button>Remove</button></td></tr>");
});

what #hazelcodes said, It would look something like this
var rootRef = firebase.database().ref().child("netflixfirebase-568e8/Usuarios");

I´ve got a solution, I added the function "childSnapshot"to the "Snapchot" that I already had.I checked each element (that is an Object) and took the properties they contained.
The code here:
var ref = firebase.database().ref ().child("Usuarios/");
ref.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
var keystl = Object.keys(childData);
console.log(childData);
console.log(keystl);
for (var i = 0; i < keystl.length; i++)
{
var k = keystl[i];
var nombre = childData[k].Nombre;
var apellido = childData[k].Apellido;
console.log(nombre, apellido);
$("#table_body").append("<tr><td>" + nombre + "</td><td>" + apellido + "</td><td><button>Remove</button></td></tr>");
}
});
});

Related

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

Retriving data from firebase web

I am trying to fetch the data for website using java script. Problem I am getting is that I am unable to get the key of Users-->history-->location-->from-->(lat,lng). I am unable to find a syntax of it.
Code I am trying is
var ref = firebase.database().ref("history/" + keys +"/location/from");
ref.on('value',gotDataa,errDataa);
function gotDataa(data){
//console.log(data.val());
var from = data.val();
var keys=Object.keys(from);
console.log(keys);
for(var i=0 ; i<keys.length;i++)
{
var k=keys[i];
var name = from[k].customer;
var phone = from[k].driver;
//console.log(name,phone,imag);
$('ul').append( '<li>' + name +" : " + phone+ '</li>' );
}
}
This should print the lat and lng of each item in the history:
var ref = firebase.database().ref("history/");
ref.on('value',gotDataa,errDataa);
function gotDataa(data){
data.forEach(function(child) {
var from = data.val().location.from;
console.log(from.lat+","+from.lng);
});
}

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

How to get the value of two nodes in Firebase?

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

Making web form for updating data in Firebase

I am making an interface to manipulate data in Firebase. I managed to make a form that inserts new data, I have a list of retrieved data, the only thing that is missing is editing/updating existing data.
I am using Foundation 6 to speed up coding HTML and CSS and I created a modal that pops up when you click on a name. Also, I made that every name has a class that is their child key in Firebase so I can open data for the right item. I've stuck here and I don't know how to make that form in modal to fill data from clicked name. Can somebody help me a bit?
Here is my code:
var ref = new Firebase("https://myname.firebaseio.com/data/users");
ref.on("child_added", function(snapshot) {
var key = snapshot.key();
var data = snapshot.val();
var name = data.name;
var city = data.city;
$("#results").append($("<li class=\"" + key + "\">" + "<a data-open=\"modal\">" + name + ", " + city + "</a></li>"));
// this is for filling up the form with loaded data
$(".name").val(name);
$(".name").focus(function(){
$(this).val(name);
});
});
Try this:
var ref = new Firebase("https://myname.firebaseio.com/data/users");
var data;
ref.on('value', function(snapshot) {
data = snapshot.val();
$("#results").empty();
Object.keys(data).forEach(function(key) {
var value = data[key];
var name = value.name;
var city = value.city;
var li = $("<li class=\"" + key + "\">" + "<a data-open=\"modal\">" + name + ", " + city + "</a></li>");
$("#results").append(li);
li.click(function() {
$('#name').val(name);
$('#city').val(city);
$('#key').val(key);
});
});
});
$('form').submit(function() {
var key = $('#key').val();
var name = $('#name').val();
var city = $('#city').val();
data[key].name = name;
data[key].city = city;
ref.set(data);
return false;
});
JSFIDDLE

Categories

Resources