External javascript array initializing - javascript

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.

Related

Apps Script: Get user input from HTML form and save them as global variables

The server side script below receives user input from an HTML form and adds these user data/input to the last available row of my Google Sheet. It´s been working pretty fine. But now I want to store some elements of the array that is in this script as global variables, so that I can re-use them later on in other server side functions bound to the same Google Sheet. I am specifically interested in the values inside lastName, email and phone. Any idea how this can be done?
Thank you so much in advance for your hints and help.
function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);
}
You can use Properties Service of Apps Script.
This service allows scripts to store strings as key-value pairs scoped
to one script, one user of a script, or one document in which an
editor add-on is used.
In your case, there are 2 options you can choose. Script Properties and User Properties.
The difference between the two is the content of Script Properties are shared to all users while User Properties is only available to the current user of a script, add-on, or web app.
Here I created an example of how to use Properties.
function setProperties(lastName = "Test Last Name", email = "Test Email", phone = "Test Phone"){
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}
function readProperties(){
var scriptProperties = PropertiesService.getScriptProperties();
Logger.log(scriptProperties.getProperties());
}
Here I run the readProperties() function first and the result is
Then I run the 'setProperties()' and rerun the readProperties() function again:
I reload the script page and ran the readProperties() function:
To add it in your script, you can set the properties in AddUserInputToSheet() and call it anywhere in your script.
Example:
function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}
function someFunction(){
var scriptProperties = PropertiesService.getScriptProperties();
var data = scriptProperties.getProperties();
var lastName = data["lastName"];
var email = data["email"];
var phone = data["phone"];
//some operations here
}
Here's an example:
function myfunk1() {
PropertiesService.getScriptProperties().setProperty('Global1',JSON.stringify(SpreadsheetApp.getActive().getSheetByName('Sheet0').getDataRange().getDisplayValues()));
}
function myfunk2() {
const vs = JSON.parse(PropertiesService.getScriptProperties().getProperty('Global1'))
SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(1,1,vs.length,vs[0].length).setValues(vs);
}

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.

Retrieve objectId in Parse

In simple, I am trying to retrieve the objectId for a particular user in parse (using Javascript). I can retrieve any other query in the database, such as username, phone, mailing address but not the objectId, here is how I retrieve the rest of the query:
var objectId = userInfo.get("objectId");
Any assistance would be greatly appreciated.
Below is more lines of the code (everything is retrieved beside objectId)
query.find({ success: function(array) {
// this means the query was a success, but we're not yet certain that we found anything
// the param to find's success is an array of PFObjects, possibly empty
if (array.length > 0) {
var userInfo = array[0];
var address = userInfo.get("address");
$scope.address = address;
var email = userInfo.get("username");
$scope.email = email;
var fullName = userInfo.get("fullName");
$scope.fullName= fullName;
var number = userInfo.get("phoneNumber");
$scope.number= number;
var objectId = userInfo.get("objectId");
$scope.objectId= objectId;
var mailingAddress = userInfo.get("mailingAddress");
$scope.mailingAddress = mailingAddress;
var plan = userInfo.get("plan");
$scope.plan = plan;
Thanks in advance
The js sdk provides an id member, so ...
$scope.objectId = userInfo.id;
As an aside, check out the JS guide on their site. It's a very well written doc. Pay particular attention to the code snippets in the objects and query sections.

pass json values across pages

I have defined a json object as
function getPost()
{
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var v = {
"name": {
"firstname": fname,
"lastname": lname
}
};
}
How can I make this JSON variable v accessible to other pages. I want to pass the JSON data across pages.
You can store data locally within the user's browser using localStorage or SessionStorage(more information) to access your data in all pages.
Take a look at this example:
localStorage.setItem('a', '{ "name" : "test"}');
eval("var myObj = " + localStorage.getItem('a'));
myObj.name; // test

Categories

Resources