I need to set a value on my Firebase realtime-database.
Here is my database organization:
Users:
U20180422:
ID: U20180422
Name: "Jason"
Surname: "Smith"
Address: "4198 Norma Avenue"
Age: "30"
creation date: "04/22/2018"
U20180311: ...
U20180304: ...
U20180215: ...
...
I make this snippet for write and it works:
<script language="javascript">
//this retrieves from the form of registration the ID of the user
var userId = document.getElementById("searchfield").value;
// Initialize Firebase
var config = {
//my configurations
};
firebase.initializeApp(config);
console.log(firebase);
var database = firebase.database();
var ref = database.ref('Users/' + userId);
var data = {
Account_validated = "OK"
}
ref.set(data)
</script>
But in this way the data that were present are deleted and only account_validated state is present in the path. So I thought I had to first retrieve all the data already in possession and then send them to the database along with the new data.
This is what is not working in my code:
//Retrieve from database
ref.on('value', gotData, errData);
function gotData(data) {
var value = data.val();
var getvalue = Object.value(value);
for (var i=0; i < value.lenght; i++) {
var k = value[i];
var name= value[k].Name;
var surname= value[k].Surname;
var address= value[k].Address;
var age= value[k].Age;
var creation_account_date= value[k].creation date;
console.log(name, surname, address, age, creation date);
}
}
function errData(err) {
console.log('Error!');
console.log(err);
}
{
snapshot.forEach(function(child) {
var childData = child.val();
var name=child.val().Name;
var surname=child.val().Surname;
var address=child.val().Address;
var age=child.val().Age;
var creation_account_date=child.val().creation date
});
});
//Write
var data = {
ID: userId,
Name: name,
Surname: surname,
Address: address,
Age: age,
creation date: creation_account_date
}
ref.set(data)
To update only the keys that you specify in your data, use update:
var data = {
Account_validated: "OK"
}
ref.update(data)
This will update only the Account_validated key under ref, and leave other child properties unmodified.
What errors are you seeing?
At first glance you've got a typo in your for loop:
for (var i=0; i < value.lenght; i++)
You've misspelt length so value.lenght will resolve to undefined and execution will just skip over the loop.
Related
I am trying to send an email to every person in an array. So I need the email adress from every person. I have a collection with the name of the person and the email adress the collection is named Benutzer/ benutzer.
Here is my code on the client:
Template.NeuesEvent.onCreated(function() {
this.subscribe('events');
this.subscribe('friends');
this.subscribe('benutzer');
});
Template.NeuesEvent.events({
"submit .add-event": function(event){
var Name = event.target.name.value;
var Beschreibung = event.target.beschreibung.value;
var Datum = event.target.Datum.value;
var Autor = Meteor.userId();
var eingeladene = []; <-- this is the array
$.each($('.FreundeCheckbox:checked'), function(){
eingeladene.push($(this).val());
});
var email = Meteor.Benutzer.findOne({"email": eingeladene});<<------
<<---- here i want to grab the email adress
if (Name == "")
{
confirm("Das Event braucht einen Namen ;)")
}
else {
Meteor.call('addEvent', Name, Beschreibung, Datum, eingeladene, Autor, email) <<--
<<------and paste the information here
event.target.name.value = "";
event.target.beschreibung.value = "";
FlowRouter.go('/meineEvents');
return false;
}
}
});
this is my method.js but the email function is not inside it now but I already know how to do that
Meteor.methods({
addEvent(Name, Beschreibung, Datum, eingeladene, Autor, email) {
Events.insert({
Name: Name,
Beschreibung: Beschreibung,
erstelltAm: new Date(),
Datum: Datum,
Eingeladen: eingeladene,
Autor: Autor
});
SSR.compileTemplate('InviteEmail', Assets.getText('Invite-Email.html'));
var emailData = {
Name: Name,
Beschreibung: Beschreibung,
erstelltAm: new Date(),
Datum: Datum,
Eingeladen: eingeladene,
Autor: Autor
};
Email.send({
to: email, <<<-----everytime a new one
from: "example#email.com",
subject: "Einladung",
html: SSR.render('InviteEmail', emailData),
});
}
});
So now you know what i try to do you can help me now with two problems first getting the email adress and second how to loop over the email.send function with every email adress again
Please do not write comments into the code without really commenting it:
Wrong:
var eingeladene = []; <-- this is the array
Better:
var eingeladene = []; // <-- this is the array
Remember, your eingeladene is an array, this returns nothing:
var email = Meteor.Benutzer.findOne({"email": eingeladene});
the correct way to do this is:
var email = Meteor.Benutzer.findOne({"email": {$in: eingeladene}});
Anyway, what I would do, I'd send array of emails to the method and do things there. Something like this.
Template.NeuesEvent.events({
"submit .add-event": function(event){
var Name = event.target.name.value;
var Beschreibung = event.target.beschreibung.value;
var Datum = event.target.Datum.value;
var Autor = Meteor.userId();
var eingeladene = [];
$.each($('.FreundeCheckbox:checked'), function(){
eingeladene.push($(this).val());
});
// we dont't need email yet
if (Name == "")
{
confirm("Das Event braucht einen Namen ;)")
}
else {
// removed Autor and email here, since we don't need it
Meteor.call('addEvent', Name, Beschreibung, Datum, eingeladene);
event.target.name.value = "";
event.target.beschreibung.value = "";
FlowRouter.go('/meineEvents');
return false;
}
}
});
Meteor.methods({
'addEvent': function(Name, Beschreibung, Datum, eingeladene) {
this.unblock();
var Autor = Meteor.users.findOne(this.userId);
Events.insert({
Name: Name,
Beschreibung: Beschreibung,
erstelltAm: new Date(),
Datum: Datum,
Eingeladen: eingeladene,
Autor: Autor
});
SSR.compileTemplate('InviteEmail', Assets.getText('Invite-Email.html'));
var emailData = {
Name: Name,
Beschreibung: Beschreibung,
erstelltAm: new Date(),
Datum: Datum,
Eingeladen: eingeladene,
Autor: Autor
};
// do you really need the fetch emails from the collection?
for (var i in eingeladene) {
var email = Meteor.Benutzer.findOne({"email": eingeladene[i]});
if (!email) {
continue;
}
Email.send({
to: email, <<<-----everytime a new one
from: "example#email.com",
subject: "Einladung",
html: SSR.render('InviteEmail', emailData),
});
}
}
});
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");
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))
})
what i need
i need to store more then data in array , such user click on div respective data must be stored in array.
like
id: 1223, city:'chicago',
id:12333,city:' new york';
code
function favaorite(sess_id,name,city,country,event_url,pointer)
{
/* store imageurl in localstorage */
var imageUrl='/images/star1_phonehover.png';
// Save data to the current local store//
// Put the object into storage
localStorage.setItem('id' ,JSON.stringify(sess_id));
// Put the object into storage
localStorage.setItem('name' ,JSON.stringify(name));
// Put the object into storage
localStorage.setItem('city',JSON.stringify(city));
// Put the object into storage
localStorage.setItem('country',JSON.stringify(country));
// Put the object into storage
localStorage.setItem('event_url',JSON.stringify(event_url));
// Put the object into storage
localStorage.setItem('imageUrl',JSON.stringify(imageUrl));
step 2.
/* fetch the data using from localstorage */
var id= [];
var name= [];
var city = [];
var country =[];
var event_url= [];
// Retrieve the object from storage
//var id, city, country,event_url;
var id = localStorage.getItem('id');
console.log(id);
id = JSON.parse(id);
var name = localStorage.getItem('name');
name = JSON.parse(name);
console.log(name);
var name = localStorage.getItem('name');
name = JSON.parse(name);
var city = localStorage.getItem('city');
city = JSON.parse(city);
console.log(city);
var country = localStorage.getItem('country');
country = JSON.parse(country);
console.log(country);
var event_url = localStorage.getItem('event_url');
event_url = JSON.parse(event_url);
///console.log(event_url);
var image_url = localStorage.getItem('imageUrl');
//event_url = JSON.parse(event_url);
alert(image_url);
console.log(image_url);
here is snapshot :
i need to store more then string in array.
i have tried by console.log(id.length)//undefined.
i have also looked loop to store more values in localstoarge.
for (var i = 0; i < localStorage.length; i++) {
console.log(localStorage.key(i))
};
You can stringify entire object and save everything at once:
localStorage.setItem('event', JSON.stringify({
id: sess_id,
name: name,
city: city,
country: country,
event_url: event_url,
imageUrl: imageUrl
}));
It will also make the code simpler and shorter:
function favaorite(sess_id, name, city, country, event_url, pointer) {
/* store imageurl in localstorage */
var imageUrl = '/images/star1_phonehover.png';
// Save data to the current local store//
if (typeof (localStorage) == 'undefined') {
console.log('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
try {
// Put the object into storage
localStorage.setItem('event', JSON.stringify({
id: sess_id,
name: name,
city: city,
country: country,
event_url: event_url,
imageUrl: imageUrl
}));
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
}
}
And retrieving saved event data you can simply do reverse:
var eventData = JSON.parse(localStorage.getItem('event'));
Try like this,
U have to create an object and fill the details on every click, push that object into an array and store that array in local storage by using JSON.stringify().
And while retrieving again parse that JSON using JSON.parse().
function favaorite(sess_id,name,city,country,event_url,pointer){
var eventData = JSON.parse(localStorage.getItem('eventData '));
if(eventData ==null){
eventData=[];
}
Var details={};
details["sess_id"]=sess_id;
details["name"]=name;
details["city"]=city;
details["country"]=country;
details["event_url"]=event_url;
details["pointer"]=pointer;
eventData.push(details);
localStorage.setItem('eventData', JSON.stringify(eventData));
}
While retrieving parse the string to json u'll get the array of those click event details.
var EventDetails=JSON.parse(localStorage.getItem('eventData '));
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.