How to display Firebase query result in HTML (undefined error) - javascript

I am trying to display Firebase query results in HTML but the browser shows "undefined" instead of the value that I see in the console.
var showData = document.getElementById("showData");
var button1 = document.getElementById("but1");
var usersRef =
firebase.database().ref('stores/').orderByChild("sid").equalTo(123);
function s2_but() { //function gets trigger when button pressed
usersRef.on('value', snap);
function snap(data) {
data2 = data.val();
console.log(data2);
showData.innerHTML = data2.sname; //sname is the name of child key
//whose value I want to show
}
};
Here is what the console shows:
entry1: {prod1: "coffee", prod2: "sandwich", sid: 123,
sname: "Java Coffee"}
__proto__:Object
Therefore, I am able to retrieve the data but I get an undefined in the browser when I use the following code to show the data in HTML.
<p id="showData"></p>
Undefined variable showing in the web-browser
I think the error happens when I am trying to call the exact value from the object using the following code but I am not sure. All the examples I have seen have done it this way. Therefore, I am confused.
showData.innerHTML = data2.sname;
In the HTML file I have both Firebase and jquery appropriately included, initialized etc.
I would greatly appreciate any help. Thanks.

I found the solution:
function snap(data) {
data2 = data.val();
data3 = data2.entry1.sname;
console.log(data3);
showData.innerHTML = data3;
};
Firebase returns a nested object with this query. entry1 is the name of the first level or key of this object. Therefore, its name has to be entered before accessing the value.
What to do if "entry1" were actually defined by a variable?

I think I was able to figure out the best way to do this. It took a while to understand the limitations of Firebase coming from an SQL background.
To query the database, I used this instead of using orderByChild():
var sid = 'entry1';
var usersRef = firebase.database().ref('stores/'
+ sid);
Now I am able to get the value of sname without having to enter the key of it in the chain:
function s2_but() {
usersRef.on('value', snap);
function snap(data) {
data2 = data.val();
data3 = data2.sname;
console.log(data3);
showData.innerHTML = data3;
};
};
This is to query a Firebase database entry that looks like this.
I hope this helps some of you looking to solve a similar problem. If you have any suggestions please let me know.

Related

Can I use two parameter event for one function?

What I want to do is change the url.
Replace the Object word with an event parameter called e1.
Replace the word field with the event parameter e2.
I know this code is not working.
But I don't know how to do it.
The following is my code that I just wrote.
function getAllFieldValue(e1,e2) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var url = 'test123.my.salesforce.com/services/data/v44.0/queryAll?q=SELECT Field FROM Object';
var url = url.replace('Object',e1);
var url = url.replace('Field',e2);
var response = UrlFetchApp.fetch(url,getUrlFetchOptions());
var json = response.getContentText();
var data = JSON.parse(json);
var fieldValues = data.records;
for(var i=0;i<fieldValues.length;i++){
var fieldValue = fieldValues[i].e;
ss.getRange(i+1,1).setValue(fieldValue);
}
}
I want to take the data from another database through this code and put it in the Google spreadsheet.
For e1, it means the object value selected in the dropbox.
For e2, it means the field of the object selected in the drop box.
Is there a way to use two event parameters for one function?
I look forward to hearing from you.
====================
Please understand that I am using a translator because I am not good at English.
Checking fieldValues[i] in Logger.log returns the following values:
[{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03VAAT
},
Name=University of Arizona
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03TAAT
},
Name=United Oil & Gas Corp.
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03ZAAT
},
Name=sForce
}]
The issues I am currently experiencing are as follows.
If I select 'Name' from the drop-down list, ec2 becomes 'Name'.
As far as I'm concerned,
var fieldName = fieldValues[i].e2 is
var fieldName = fieldValues[i].Name
It means that.
I think fieldValues[i].e2 should return the values of University of Arizona, United Oil & Gas Corp, sForce.
But in reality nothing is returned.
var fieldName = fieldValues[i].Name works properly.
I think there is a problem with fieldValues[i].e2
This is the problem I'm currently experiencing.
There was no problem with the parameters e1, e2, which I thought was a problem. The reason why the code did not work is because of the for loop var fieldValue = fieldValues[i].e; Because it didn't work properly.
var fieldName = fieldValues[i].e2
to
var fieldName = fieldValues[i][e2]
After modifying it like this, the code works properly.

Access specific data on Json - NodeJS

I'm trying to access data from a json but i can't... I have tried some explanations i found on the internet, but i guess there is something wrong on my code.
I'm getting data from a sql server database using the following code:
async function getLogin1(Operador, Senha) {
try {
let pool = await sql.connect(config);
let getLogin1 = await pool.request()
.input('input_parameter', sql.VarChar, Operador)
.input('input_parameter1', sql.VarChar, Senha)
.query("SELECT Codigo, Operador, Senha FROM Usuario where Operador = #input_parameter and Senha = #input_parameter1");
return getLogin1.recordsets;
}
catch (error) {
console.log(error);
}
}
So i get the recordsets here and put in a json:
router.route("/Login1").get((request, response) => {
console.log(request.body.operador);
console.log(request.body.senha);
Operador = request.body.operador;
Senha = request.body.senha;
dboperations.getLogin1(Operador, Senha).then(result => {
console.log(Operador, Senha);
response.json(result);
var json = JSON.stringify(result);
console.log(json);
})
})
On the console it shows the json:
[[{"Codigo":1,"Operador":"Username","Senha":"123456"}]]
I would like to get the individual data (codigo, operador and senha) to put in a individual string each one, but i cant access the data.
When I try like json[0] for example i get all the json (because my json has every info on the first position i guess), and when i try json.Codigo (for example) i get a "undefined" error.
What am i doing wrong and what the best way to solve?
And sorry for the low knowledge, this is my very first api.
(And yes, this is a login code and its not the best way to treat user data but its a very small system for intern use)
Your JSON "result" is:
[[{"Codigo":1,"Operador":"MASTER","Senha":"TERA0205"}]]
So it is an array of array containing one object with keys Codigo, Operador, Senha.
To get the value of the Codigo of that object you would likely need to
access it like
var CodigoVal = result[0][0].Codigo; // 1
var OperadorVal = result[0][0].Operador; // "MASTER"
Looks like json has nested array, if so json[0] will give inner array so you have to probably do like json[0][0].Codigo
[
[
{ "Codigo":1,
"Operador":"Username",
"Senha":"123456"
}
]
]
If we look at the JSON you posted above, we have an array which has an array with an object at its first index.
So to get access to that object you need to do:
const obj = json[0][0];
Now from obj you can extract Codigo, Operado and Senha like
const condigo = obg.Condigo;
const operado = obg.Operado;
const senha = obg.Senha;
You can also directly access them like
var codigo = json[0][0].Codigo;
var operador = json[0][0].Operador;
var senha = json[0][0].Senha;
json.Codigo doesnt work because your json has a array in it. Which has the object you are trying to get data from.
json[0] returns everything because that gives you the object from that array
so if you want Codigo try json[0][0].Codigo
I hope this helped you!

Accessing specific key and its value in a object returned from firebase

I have a JS function which goes into a Firebase realtime database to read some objects. The objects it checks have several fields but I only want one of these, the URL key and its value. Here is my function which retrieves the data:
const dbRefObject = firebase.database().ref('gifs');
dbRefObject.on('value', gotData);
function gotData(data){
dbRefObject.once('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
console.log(childKey, " ", childData);
})
}
)
}
The data that is actually returned looks like this:
Content Description: "Hack The Planet"
Date Added: "08/04/2020"
Permission: "Admin"
URL: "https://firebasestorage.googleapis.com/v0/b/..."
I only want to access the URL key and its data but I cant seem to do so. I have tried doing childData[3] but it doesn't work. Any help would be appreciated.
Child values in Realtime Database are always specified by their name, not by their order. To get the URL from the snapshot, you will want to use:
var childData = childSnapshot.val();
var URL = childData.URL;
Note that the names of the children become the keys of the object returned by val().

Delete a field from Firestore, with a dynamic key

I am trying to delete a single field from a Document in Firestore
The Key of the field is held in a variable e.g.
var userId = "random-id-1"
In the document I have a field of members structured like this:
{
members:{
random-id-1:true,
random-id-2:true
}
}
I would like to delete random-id-1:true, but keep random-id-2:true
How is this possible without getting the entire members object and writing an updated object?
I have tried this, however I get the error: Document references must have an even number of segments
and I also tried this:
db.collection('groups').doc(this.props.groupId).set({
members: {
[userId]: firebase.firestore.FieldValue.delete()
}
},{merge: true})
However I get the error: Function DocumentReference.update() called with invalid data. FieldValue.delete() can only appear at the top level of your update data
Thanks for any help
I have managed to delete a field like this:
let userId = "this-is-my-user-id"
let groupId = "this-is-my-group-id"
db.collection('groups').doc(groupId).update({
['members.' + userId]: firebase.firestore.FieldValue.delete()
})
This is using the dot operator method described here
Please let me know if there are any alternative methods to this
Thanks
I had to import FieldValue
https://firebase.google.com/docs/firestore/manage-data/delete-data#fields
// Get the `FieldValue` object
var FieldValue = require('firebase-admin').firestore.FieldValue;
// Create a document reference
var cityRef = db.collection('cities').doc('BJ');
// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
capital: FieldValue.delete()
});

Display data from sqlite DB with AngularJS

I like to collect data from an android app and store them into sqlite DB - no problem so far.
But now I want to list these data using AngularJS, ng-repeat command.
I take the data from the DB via db.transaction(function(tx) tx.execSql...) but now how to format the data rows so that ng-repeat can read them ?
I tried an array of objects, I tried building a JSON string - both not working, I got a ngRepeat error.
var app = angular.module('demo',[]);
app.controller("MainController", function($scope){
// gets the tasks from the DB as json object
db.transaction(function(tx){
tx.executeSql("SELECT task,task_detail,task_date FROM task", [],
function(tx, rs){
var rows = rs.rows;
if (rows.length>0) {
var json_arr = [];
for(var i = 0; i < rows.length; i++) {
var row = rows.item(i);
var obj = {task: row.task,detail:row.task_detail,datum:row.task_date};
json_arr.push(obj);
}
}
var json_str = JSON.stringify(json_arr);
alert("json_str: "+ json_str); // WORKING !
sessionStorage.tasks = json_arr; // to get result out of db.transaction...
})
}); // end db.transaction
$scope.tasks = sessionStorage.tasks;
-> when i display {{tasks}} it appears as: [object,object]
and ng-repeat doesnt work
Otherwise if i use the stringified json, it displays correctly in {{tasks}} but ng-repeat causes again error.
Another real "dirty" way to get the result of the query into $scope is the sessionStorage thing - I dont like it this way but I cant see another possibility to set the $scope variable to the JSON (or whatever) result of the DB query. Maybe someone has a better idea ? ;)
Any ideas ? Thanks a lot, Chris

Categories