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);
Related
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.
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),
});
}
}
});
I want to signup new users (through auth) and then add them (with their names and other info) to my user list database in realtime DB. I can't figure out what I'm doing wrong. Authentication works great but the new user is not being added to the DB.
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
in the code below, I register them then add their names to the DB and then send a verification email.
function handleRegister() {
var ref = firebase.database().ref();
console.log(email);
console.log(fname);
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
var uid = firebase.auth().currentUser.uid;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
firebase.auth().onAuthStateChanged(user => {
if(user) {
var postData = {
Fullname: fname + lname,
email: email,
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/Users/' + uid ] = postData;
return firebase.database().ref().update(updates);
}
})
} else {
console.log(error);
}
})
Authentication and send email verification works fine but names are not being added to the DB. Also if there is a better approach to achieve auth,add to DB and send email verification, please let me know. Please help.
This is the updated addition
var addusertoDB = function(user){
var uid = firebase.getAuth().uid;
var postData = {
Firstname: fname,
Lastname: lname,
email: email,
}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('Users').push().uid
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/Users/' + newPostKey] = postData;
// updates['/user-posts/' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
and handle register has been updated to
firebase.auth().createUserWithEmailAndPassword(email, password).then(
addusertoDB).catch(handleCreateUserError);
it's finally being added to the DB (without the uid) but firebase.getAuth().uid is not getting the uid. the error I'm getting is "firebase.getAuth is not a function"
You are trying to handle both the errors and the user update in the same function you have passed to catch(). This means that any code inside that function is only run when firebase.auth().createUserWithEmailAndPassword(email, password) fails.
From the firebase documentation:
createUserWithEmailAndPassword
createUserWithEmailAndPassword(email, password) returns
firebase.Promise containing non-null firebase.User
Creates a new user account associated with the specified email address
and password.
On successful creation of the user account, this user will also be
signed in to your application.
This means that on the successful creation of a user you will have access to the new user via a callback passed into then().
You probably want something like this:
var doSomethingWithNewUser = function(user) {
// Manipulate the newly created User however you like here.
// You don't have to sign them in again.
};
var handleCreateUserError = function(error) {
var errorCode = error.code;
var errorMessage = error.message;
// Do whatever you want with the error codes.
};
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(doSomethingWithNewUser)
.catch(handleCreateUserError);
I have an external client in a js file.
function client(Id,userName,code,type, firstName, SurName, address, phoneNum, Email)
{
this.Id = Id;
this.userName = userName;
this.code = code;
this.firstName=firstName;
this.SurName=SurName;
this.ddress=address;
this.phoneNum=phoneNum;
this.Email =Email;
this.clientAccounts = [];
this.addAccount = function(account)
{
this.clientAccounts.push(account);
};
}
and I have an html page. In it I have a script:
<script type="text/javascript">
var myClients =new Array();
myClients[0]= {firstName:"John", SurName: "Doe" ,Id:11,Password:1234, Address:"Some where over the rainbow", Pnumber:0523456789, Email:"yeah#gmail.com", Type: "regular"};
var account = new account(232, "young");
var deposit = new depositAccount(232, "young", 1000, 2555);
myClients[0].addAccount(deposit);
//clientAccounts.push(myClients[0]);
</script>
Each client I initialize should have multiple accounts. Now I'm not sure how do I set the account array of the client. should it be a part of the constructor(inside the parentheses)?
Because right now I can't use this array or get its data (I'm trying using another js file).
Why don't you actually make use of the constructor:
myClients[0] = new client(11, "username", 1234, "regular", "John", "Doe", "Somewhere over the rainbow", "0523456789", "yeah#gmail.com");
Then the "addAccount" method should work.
Otherwise you just have an object with some properties(attributes), but not of the class client.
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.