Firebase: show children nodes in calendar - javascript

Is it possible to implement a calendar on my website which shows user submissions by their date on a calendar?
The following code captures some test variables and I would like them shown in the calendar by the date they were submitted.
function startDatabaseQueries() {
alert("StartQueries");
// Get current user info
var myUserId = firebase.auth().currentUser.uid;
var username = firebase.auth().currentUser.displayName;
// Get posts
alert("1");
var testRef = firebase.database().ref('posts').orderByKey();
testRef.once('value', function(snapshot) {
var results = [];
snapshot.forEach(function(childSnapshot) {
//var key = childSnapshot.key;
var childData = childSnapshot.val();
// console.log(childData);
var author = childSnapshot.val().author;
console.log(childSnapshot);
document.getElementById("demo").innerHTML = author;
});
});
}
The
console.log(childSnapshot)
shows the following code in the console: (Variable results omitted)
Author:
AuthorPic:
submitted:
title:
uid:

I would recommend grabbing the date as well and store it on the database with the format "yyyyMMdd". Then, when you want to read the data, you would simply use:
var testRef = firebase.database().ref('posts').orderByChild("dateAdded");

Related

How to retrieve data from different parent nodes in a Firebase Database in JavaScript

I have the following database:
I want to retrieve the value of name given a specific ID value in JavaScript.
Right now I have the following code, but it doesnt seem to acces both ID and name nodes:
var user = db.ref("Users").orderByChild("ID").equalTo("12345");
users.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
...
This can be achieved with the code below:
var ref = db.ref("Users").orderByChild("ID/value").equalTo("12345");
ref.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
var name = childData.name.value;
});
});

when retrieving data from firebase database the browser shows undefined

I tried to retrieve data from firebase database. The returned data shows like
undefined undefined undefined
the code I used is
var query = firebase.database().ref().child("users/-Ly-dBv9xSiBf-UO0A8Q").orderByKey();
query.once("value") .then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val().messageText;
document.writeln(childData);
});
});
It shows undefined because first, the reference is at the random ID node therefore you don't have to loop. Second, you don't have an attribute called messageText in your database. Your code should be like this:
var query = firebase.database().ref().child("users/-Ly-dBv9xSiBf-UO0A8Q").orderByKey();
query.once("value") .then(function(snapshot) {
var childData = snapshot.val().password;
var userId = snapshot.val().user_id;
document.writeln(childData);
});

Show all objects present in localStorage on a webpage

I am storing my data from a form in localstorage in the following format:
Object {title: "dsadasds", dueDate: "dsadasdsa", summary: "dsadadas", body: "dasdasdas"}
Object {title: "dasdadsa", dueDate: "dasdasdadasda", summary: "dsadasdasd", body: "dasdasdas"}
This data is stored in localstorage every time a user submits the form. Now in a different page 'localhost:3000/notes' i wanna show all these objects stored in localStorage. Currently with the following code, its just showing the last object submitted.
var form = $('#form'),
formTitle = $('#title'),
formDueDate = $('#dueDate'),
formSummary = $('#summary'),
formBody = $('#body');
var title = formTitle.val();
var dueDate = formDueDate.val();
var summary = formSummary.val();
var body = formBody.val();
var newContent2 = $('#new-content2')
var test = {};
test = {
title: title,
dueDate: dueDate,
summary: summary,
body: body
}
localStorage.setItem('test', JSON.stringify(test));
var LocalStoredData = JSON.parse(localStorage.getItem('test'));
console.log(LocalStoredData);
//for retrieving data from locastorage
var retrievedData = localStorage.getItem('test');
var text = JSON.parse(retrievedData);
var showTitle = text["title"];
var showDueDate= text["dueDate"];
var showSummary = text["summary"];
var showBody = text["body"];
$('#showTitle').html(showTitle);
$('#showDueDate').html(showDueDate);
$('#showSummary').html(showSummary);
$('#showBody').html(showBody);
I need to loop trough all the objects (or any other mechanism) to extract all the objects from localStorage and display them in appropriate div on the web page. I tried putting the retrieval code in the loop:
for(var i=0;i<localStorage.length;i++)
but using this loop its not showing anything. How can I show all the objects present in my localStorage.
You're looking for
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
var item = localStorage.getItem(key);
try {
item = JSON.parse(item);
} catch(e) {
console.log(key+" is not in JSON format");
}
…
}
You can also easily get all the contents of LocalStorage using Object.keys:
Object.keys(localStorage).forEach(key => {
console.log(key, localStorage.getItem(key))
})

Firebase - return user uid and set user meta data value to different node

I am trying to retrieve data from a Users node in Firebase and use the retrieved data in a set() to another node. Specifically I want to use my user UID to look at which "branch" the user belongs to and then use the value in the set()
I have the following snapshot to get the "branch" of the user. It logs to the console the correct value
var ref = new Firebase("firebase/url");
var authData = ref.getAuth();
var userUID = authData.uid
var userRef = new Firebase("firebase/URL" + userUID);
userRef.once("value", userBranch)
function userBranch(snapshot) {
var data = snapshot.val();
console.log(data.branch);
};
With the returned "branch" value I want to use it in the following set()
var postsRef = ref.child("Posts");
var newPostRef = postsRef.push();
var postID = newPostRef.key();
postsRef.child(postID).set({
branch: data.branch})
What is the best way to take the value out of the function userBranch so I can use it in my set()?
You are using .once a little bit wrong, but you have the right idea.
var ref = new Firebase("firebase/url");
var authData = ref.getAuth();
var userUID = authData.uid
var userRef = new Firebase("firebase/URL" + userUID);
// Second parameter is callback function that receives data (snapshot)
userRef.once("value", function(snapshot) {)
var data = snapshot.val();
console.log(data.branch);
// Save value at data.branch
var dataBranch = data.branch;
var postsRef = ref.child("Posts");
var newPostRef = postsRef.push();
var postID = newPostRef.key();
// Save it, erasing all previous data at location
postsRef.child(postID).set({
"branch": dataBranch
});
};
You were a little mixed up with the second parameter for .once.
References:
Firebase | .push
Firebase | .once
Firebase | .set

Titanium Studio, JavaScript and SQL Error... Cant figure it out

var url = "http://api.reddit.com/";
var dataArray = [];
var working = function(){
var getData = JSON.parse(this.responseText);
var titles = getData.data.children;
for(var i=0, j=titles.length; i<j; i++)
{
var title = titles[i].data.title;
dataArray.push({
title: title,
favorite: 0
});
}
save(dataArray);
}; //working
var save = function(arg){
console.log(arg);
var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name TEXT, favorite INTEGER)');
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)', arg.title, arg.favorite);
var rowID = db.lastInsertRowId;
//newRow.id = rowID;
//rows.close();
db.close();
gather();
};
var dataContent = [];
var gather = function(){
var db = Ti.Database.open("newData");
var dbRows = db.execute("SELECT name, favorite FROM redditTitles"); // Returns a Result Set object
while(dbRows.isValidRow()){
dataContent.push({
title: dbRows.fieldByName("name"),
fav: dbRows.fieldByName("favorite")
});
console.log("dataContent: "+ dataContent.title);
dbRows.next();
}
dbRows.close();
db.close();
console.log(dataContent);
userInterAPI();
};
var error = function(){
alert("Please check your network connection and try again.");
};
var client = Ti.Network.createHTTPClient({
onload: working,
onerror: error,
timeout: 5000
});
client.open("GET", url);
client.send();
So Basically me and my instructor have been scratching our heads trying to figure out why the arg will show all of the data but after the data is saved and we go to re console log it out, it will show up as null. Not sure why. Someone please help me!
You are saving just one item (Incorrectly - that's why is undefined). If you want to save everything you have to iterate through whole array.
var save = function(arg) {
console.log(arg);
var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name TEXT, favorite INTEGER)');
db.execute("BEGIN"); // Transaction
arg.forEach(function(item) {
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)', item.title, item.favorite);
//var rowID = db.lastInsertRowId;
});
db.execute("COMMIT");
db.close();
gather();
};
In the function called gather - if you want to see selected title you should use:
console.log(dbRows.fieldByName("name"))
alternatively (This is what you wanted to use):
console.log(dataContent[dataContent.length - 1].title)
instead of
console.log(dataContent.title); // dataContent is an Array.
*Of course you better avoid using dataContent.length in every iteration. That's just an example.

Categories

Resources