Get Email Address of every Person in Array in Meteor - javascript

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

Related

Can Not Store Data From Contact Form To Firebase

I am trying to send the data of my user to firebase using the code given below:
var firestore = firebase.firestore();
var messagesRef = firestore.collection("BookingData");
//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
//get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');
}
// function to get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
//save messages
function saveMessage(email, packageFields, name, phone, date) {
messageRef.add({
email:email,
packageFields:packageFields,
name:name,
phone:phone,
date:date
}).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
But nothing is happening.
I am not able to send the data to firebase databse.
it also shows a warning called:
[2020-05-30T03:38:27.083Z] #firebase/app:
Warning: Firebase is already defined in the global scope. Please make sure
Firebase library is only loaded once.
How can I Solve this problem? Please Help/\
Thanks in advance.
Ok, I got The Error I was Not calling The Function. The correct code is:
var firestore = firebase.firestore();
var messagesRef = firestore.collection("BookingData");
//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
//get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');
saveMessage(email, packageFields, name, phone, date);
}
// function to get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
//save messages
function saveMessage(email, packageFields, name, phone, date) {
messageRef.add({
email:email,
packageFields:packageFields,
name:name,
phone:phone,
date:date
}).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}

Javascript insert prompt value to another function object

I'm trying to put the values at addUser function to push to another function object. I dont how and what to put at the prompt value to .id and .pwd.
var memArray =[];
function addUserObject(id, password){
this.id = id;
this.pwd = password
}
var addUserObj = new addUserObject ("")
// i dont how and what to put the prompt value to .id and .pwd
memArray.push(addUserObj);
console.log(memArray)
function addUser(){
var addUsername = prompt ("Type your username");
var addPwd = prompt ("Type your password");
addUserObject(addUsername,addPwd)
At the risk of not having understood your problem, you can't add the user until you know the username and password (until the prompt requests are finished).
Is this what you are trying to do?:
// Initialize an empty array
var memArray =[];
// Define helper function to add a user to the array
function addUserObject(id, password){
// Define a user object
var userObj = {
id: id,
password: password
};
// Push the new user into the array
memArray.push(userObj);
}
// Define a function that requests user and pwd
function addUser(){
// Request username and pwd
var addUsername = prompt ("Type your username");
var addPwd = prompt ("Type your password");
// Call to add the user to the array
addUserObject(addUsername, addPwd);
}
// Call the 'addUser' function to request a new user
addUser();
// Print the array to console (it should contain one user)
console.log(memArray);
I have commented the code excessively just so you understand.
One way is to add the functionality to this, same as the properties you create:
function addUserObject(id, password){
this.id = id;
this.pwd = password;
this.addUsername = function(){this.id = prompt("Type your username")}.bind(this);
this.addPwd = function(){this.pwd = prompt("Type your password")}.bind(this);
};
var addUserObj = new addUserObject();
//REM: Adding username
addUserObj.addUsername();
console.log(addUserObj);
//REM: Adding paddword
addUserObj.addPwd();
console.log(addUserObj);
The second way is to ask for it on creation:
function addUserObject(id, password){
this.id = id;
this.pwd = password;
}
var addUserObj = new addUserObject(prompt("name?"), prompt("pw?"));
console.log(addUserObj);
Once you create an object, it has to contain properties along with methods, so it's ok to implement all inside an instance.
var memArray =[];
function addUserObject(){
var id, pwd;
this.getData = function(){
return {
id: this.id,
pwd: this.pwd
}
}
this.setData = function(){
this.id = prompt ("Type your username");
this.pwd = prompt ("Type your password");
}
return this.setData();
}
var user = new addUserObject;
memArray.push(user.getData());
console.log(memArray)
If you want to use constructors functions, then you can create a function which return a new object:
function userObject(id, name, password){
this.id = id;
this.name = name;
this.pwd = password
}
let userBob = new userObject(1, 'Bob', 'fooPsw');
let userJoseph = new userObject(2, 'Joseph', 'barPsw');
let userJohn = new userObject(3, 'John', 'barPsw');
and then just push these objects into array:
let users = [];
function addUser(id, name, password)
{
let user = new userObject(id, name, password);
users.push(user);
}
addUser(1, 'Bob', 'fooPsw');
addUser(2, 'Joseph', 'barPsw');
addUser(3, 'John', 'barPsw');
The whole code looks like this:
function userObject(id, name, password){
this.id = id;
this.name = name;
this.pwd = password
}
let users = [];
function addUser(id, name, password)
{
let user = new userObject(id, name, password);
users.push(user);
}
addUser(1, 'Bob', 'fooPsw');
addUser(2, 'Joseph', 'barPsw');
addUser(3, 'John', 'barPsw');
console.log(users);

How to update data without deleting anything else?

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.

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.

function doesn't read the object

can some one please tell me how can i make the send function read the email object from the next code?
var email = {
to: 'google#gmail.com',
subject: 'new email',
text: 'helloWorld'
}
function send() {
var sendMe = new email();
console.log(sendMe.subject);
}
send();​
i get this error i also tried to declare the email as follow :
var email = new object();
and it didn't work
Uncaught TypeError: object is not a function
You are either trying to do this:
var email = { to: 'google#gmail.com', subject: 'new email', text: 'helloWorld' }
function send()
{
console.log(email.subject);
}
send();
Or this
function email()
{
this.to = 'google#gmail.com';
this.subject = 'new email';
this.text = 'helloworld';
}
function send()
{
var sendMe = new email();
console.log(sendMe.subject);
}
send();
I'm not sure which, so I made an example of both. Cheers
It sounds like you want sendMe to point at the same data email is holding:
var email = { ...} ;
function send() {
var sendMe = email;
console.log(sendMe.subject);
}
But if this is the case, you might as well skip the extra variable and just use email directly:
var email = { ...} ;
function send() {
console.log(email.subject);
}
You can't use an identifier as an object constructor unless it's a function.
If you want a reference to the object that you created, just copy it from the variable:
var sendMe = email;
You have to return object:
var email = function() {
return {
to: 'google#gmail.com',
subject: 'new email',
text: 'helloWorld'
}
};
and then
function send() {
var sendMe = new email();
console.log(sendMe.subject);
}
should work.

Categories

Resources