Storing information in cookies - javascript

Does anyone know powerfull class for storing information in cookies?
I just want write something like:
var cookieStorage = new cookieStorage(100); // 100 - time to store data
var apple = {size:10, color:'red',weight:100};
cookieStorage.set('MyApple',apple);
var restoredApple = cookieStorage.get('MyApple');
My implementation(without time to storing)
var cookieStorage = {
set: function (key, value) {
$.cookie(key, $.toJSON(value));
},
get: function (key) {
var json = $.cookie(key);
return $.parseJSON(json);
}
}
Here is cookie plugin

You can use the JSON library to achieve this. You can download JSON here: https://github.com/douglascrockford/JSON-js
I created a simple example for you. If you want to make it short, you can use JQuery-cookie.
function setCookie(){
var current = new Array();
var user = new Object();
user.FirstName = "Robby";
user.LastName = "Shaw";
current.push(user); //The test value
var exdate=new Date();
exdate.setDate(exdate.getDate()+5); //Expire in 5 days
var cname = "test"; //cookie name
var value = JSON.stringify(current); //Parse the array
document.cookie=cname+ "=" +escape(value)+ ";expires="+exdate.toGMTString();
}
function getCookie(){
var current = new Array();
if (document.cookie.length>0){
c_start=document.cookie.indexOf("test=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
current = JSON.parse(unescape(document.cookie.substring(c_start,c_end)));
alert(current[0].FirstName+","+current[0].LastName);
}
}
}

Related

Pass var Value to another var For Use With body.replaceText

I'm working on a script that takes my Google Forms data and performs a replace function on a predetermined template Doc file using body.replaceText which is working fine. I've copied a truncated version of that below.
I can submit a form and it will replace the values of the template as designed but there are some multiple-choice (Yes or No) questions that are represented by checkboxes on the template Doc.
I've figured out how to Logger.log the checkboxes via unicode but how do I get var systemOperational.getValue = "yes" to assign a value to var systemOperationalYes using IF/Else?
Trying to have "If systemOperational value is Yes then systemOperationalYes = unicode \u2611 Else systemOperationalYes = unicode \u2610".
Pardon me if any of this sounds amateur. This is literally my first go at this.
//e.values is an array of form values
var timestamp = e.values[0];
var emailAddress = e.values[1];
var jobID = e.values[2];
var storeName = e.values[3];
var systemOperational = e.values[22];
if (systemOperational.getValue = "yes") {
var systemOperationalYes = "\u2611";
Logger.log("\u2611");
} else {
var systemOperationalYes = "\u2610";
Logger.log("\u2610");
}
// Locat template file
var files = DriveApp.getFolderById("XXXXXXX").searchFiles('title contains "'+ jobID +'"');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getId());
}
//file is the template file, and you get it by ID
var templateFile = DriveApp.getFileById(file.getId());
//We can make a copy of the template, name it, and optionally tell it what folder to live in
//file.makeCopy will return a Google Drive file object
var responseFolder = DriveApp.getFolderById("XXXXXXXXX");
//Converts dateSigned var to MM-dd-yyyy for use in file name
var convertedDate = new Date(dateSigned);
Logger.log(convertedDate);
var formatSignDate = Utilities.formatDate(convertedDate, "GMT-5", "MM-dd-yyyy");
Logger.log(formatSignDate);
var folder = responseFolder.createFolder(storeName + '-' + jobID + '-' + formatSignDate);
var copy = templateFile.makeCopy(storeName + '-' + jobID + '-' + formatSignDate, folder);
//Once we've got the new file created, we need to open it as a document by using its ID
var doc = DocumentApp.openById(copy.getId());
//Since everything we need to change is in the body, we need to get that
var body = doc.getBody();
//Then we call all of our replaceText methods
body.replaceText('{{SYSOPY}}', systemOperationalYes);
//Lastly we save and close the document to persist our changes
doc.saveAndClose();
// Convert temporary document to PDF
var pdf = DriveApp.getFileById(copy.getId()).getAs("application/pdf")
var url = DriveApp.getFolderById(folder.getId()).createFile(pdf);
// Delete temp file
//DriveApp.getFileById(templateFile.getId()).setTrashed(true);
}```
try it this way:
var timestamp = e.values[0];
var emailAddress = e.values[1];
var jobID = e.values[2];
var storeName = e.values[3];
var systemOperationalYes;
if (e.values[22] = "yes") {
systemOperationalYes = "\u2611";
Logger.log("\u2611");
} else {
systemOperationalYes = "\u2610";
Logger.log("\u2610");
}

Dynamic Javascript Variable?

I am not very sure how to name the question. What i am trying to achieve is this..
I have a set of Global Variable, they will need to be replicated over and over, but assigned with different set's name example. For example
var start
var end
var time
And i have many set/model that i have to create and change, so i am wondering if it is possible to create 1 set and i just have a var modelnumber which then i can just copy and paste them and change the modelnumber so i wont have to change thousands of variable names?
Example
var modelnumber = "1";
var modelstart = modelnumber + "modelstart";
var modelend = modelnumber + "modelend";
var modeltime = modelnumber + "modeltime";
Edit: To provide more info
So i have model1.js , model2.js model3.js and so on....and all the variable names function names are the same, and to save me time, i want to write 1 set of code that i can just change the var modelname at the top of each field so i wont have to change the thousands of variable names and function names..
You can always write a function:
function createVariables(modelNumber) {
window[modelNumber + 'modelstart'] = 1;
window[modelNumber + 'modelend'] = 2;
window[modelNumber = 'modeltime'] = 3;
}
createVariables(1);
Or change it to however you want. :)
UPDATE: (use global in place of window for NodeJS).
I think you're looking for a normal object literal. You can specify the property keys of the object with strings, which will give you the dynamic effect you're looking for.
Here's an example, using a for loop to populate the object.
var models = {};
var number_of_keys = 1000;
for(var i = 1; i < number_of_keys; i++) {
var keyName = 'model' + i;
var model = {
'start': i + 'modelstart',
'end': i + 'modelend',
'time': i + 'modeltime'
}
models[keyName] = model;
}
console.log(models);
Update:
As an example of how you could access your populated models, consider the following:
// You can effectively replace the `1` in this example with any number:
var model1 = models['model1'];
// model1 would be:
// {
// 'start': '1modelstart',
// 'end' : '1modelend',
// 'time': '1modeltime'
// }
var start1 = model1.start;
var end1 = model1.end;
var time1 = model1.time;
// Pseudo-code
var modelN = models['modelN'];
var startN = modelN.start;
var endN = modelN.end;
var timeN = modelN.time;
HTH
You could (should?) use an object or an array of objects.
For example:
// The "Model"
var Model = function(start,end,time) {
this.start = start;
this.end = end;
this.time = time;
}
// One option.
// Assign "Model" to the models
var models = {
'm1': new Model(x,y,z),
'm2': new Model(a,b,c)
}
// Access values
if (models.m1) {
alert("m1 end:["+ models.m1.end +"]");
}
// Add a "new" model
models['ace'] = new Model(r,s,t);
// or even
models.club = new Model(e,f,g);
You could also extend it like so:
Model.prototype.debug = function(id) {
if (id) {
console.log("model id:["+ id +"]");
}
console.log("start:["+ this.start +"]");
console.log("end:["+ this.end +"]");
console.log("time:["+ this.time +"]");
}
Which you would call like so:
models.m1.debug();
Or even:
for(x in models) {
models[x].debug(x);
}
Here is a code snippet example.
var Model = function(start,end,time) {
this.start = start;
this.end = end;
this.time = time;
}
Model.prototype.debug = function(id) {
if (id) {
console.log("model id:["+ id +"]");
}
console.log("start:["+ this.start +"]");
console.log("end:["+ this.end +"]");
console.log("time:["+ this.time +"]");
}
var models = {
'm1' : new Model('x','y','z'),
'm2' : new Model('a','b','c')
};
models.ace = new Model('r','s','t');
for(x in models) {
models[x].debug(x);
}

Google Script appendRow() fails

Everytime I try appendRow() I just get [Ljava.lang.Object;#4ed3710 in my spreadsheet.
function my() { //does not work
var ssMASTER = SpreadsheetApp.openById('1e4-----vQX');
var shMASTER = ssMASTER.getSheetByName('master_request');
var valuesMASTER = shMASTER.getDataRange().getValues();
var valuesPermaWrt = new Array();
valuesPermaWrt.push(["WhatEverItem"]);
Logger.log("writing:" + valuesPermaWrt); //Log: WhatEverItem
ssMASTER.appendRow([valuesPermaWrt]); //fails
}
I followed the solution from elias91:
var orderString = timeStamp + "," + ordNum + "," + clc + "," + orderRng.toString();
var orderValues = orderString.split(",");
from the Google Sheets: How to appendRow with 2d getValues array?
to create my failed version like here:
function blablaArray() { //does not work
var ssMASTER = SpreadsheetApp.openById('1e61------IuFV');
var shMASTER = ssMASTER.getSheetByName('master_request');
var valuesMASTER = shMASTER.getDataRange().getValues();
Logger.log("writing:" + valuesMASTER[0]);
//Log: [Timestamp, currently, scheduled in, Pin number]
var preappendMe = valuesMASTER[0].toString();
var appendMe = new Array();
var appendMe = preappendMe.split(",");
ssMASTER.appendRow([appendMe]); //fails
}
I know appendRow() is described here https://developers.google.com/apps-script/reference/spreadsheet/sheet#activate. But copy-pasting variables 10 times seems like a hack rather a programmatic solution, so I want it to be done through Array and not like here through each String variable.
function blablaSS() { //works fine
var ssMASTER = SpreadsheetApp.openById('1e61-----xAU');
var shMASTER = ssMASTER.getSheetByName('master_request');
var singularvalue = "ede";
ssMASTER.appendRow(["a man", singularvalue, "panama"]);
}
Try calling JSON.stringify() on your data before appending to the Google Sheet.
var valuesPermaWrt = new Array();
valuesPermaWrt.push(JSON.stringify(["WhatEverItem"]));
ssMASTER.appendRow(valuesPermaWrt);

ERROR: The collection has not been initialized

I am querying the contents of the Managed Metadata using the code below. I am encountering an error
The collection has not been initialized
when I am in the var level2TermsEnum = level2Terms.getEnumerator();
I have read that this is because of the deferred and promise of JavaScript and I can't seem to understand it. Maybe you could help me shed some light on here.
$(document).ready(function () {
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js", function () {
$.getScript(scriptbase + "SP.Taxonomy.js", function () {
context = SP.ClientContext.get_current();
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Term Store under which to create the group.
var termStore = termStores.getByName("Managed Metadata Service");
var termSet = termStore.getTermSet("7b6ee52v-3709-4181-a14d-b953f2ad0aad");
//Call your code here.
GetTermsFromTaxonomyStore();
});
});
});
var json = "";
function GetTermsFromTaxonomyStore() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStores = taxSession.get_termStores();
//Term Store under which to create the term.
//var termStore = taxSession.getDefaultSiteCollectionTermStore();
var termStore = termStores.getByName("Managed Metadata Service");
//Pass ID of the Meetings Term Set
var termSet = termStore.getTermSet("7b6ee52v-3709-4181-a14d-b953f2ad0aad");
var terms = termSet.get_terms();
context.load(terms);
context.executeQueryAsync(function () {
var level1Terms = terms.getEnumerator();
while (level1Terms.moveNext()) { //iterate thru Level1
var level1 = level1Terms.get_current();
if (level1.get_termsCount() > 0) { //check if Level1 has child
var level2Terms = level1.get_terms(); //get level2 terms of level 1 term
**var level2TermsEnum = level2Terms.getEnumerator();**
while (level2TermsEnum.moveNext())
{
var level2Term = level2TermsEnum.get_current();
var level2TermName = level2Term.get_name();
termsList += '"Level1":"' + level2Term.get_name() + '","Level2":"' + level2TermName + '"';
}
}
//console.log(currentTerm.get_name());
}
alert(termsList);
}, function (sender, args) {
console.log(args.get_message());
});
}
When the client object model returns a collection of objects for you, if each of those objects has its own sub-collections, they won't be initialized unless you explicitly ask for them to be loaded.
Similar to the answer provided here, you should be able to update your call to context.load() with an additional parameter telling it what to load.
I believe something like the below code will work, but I haven't tested it:
context.load(terms,"Include(Name,Terms,Terms.Include(Name))");

Javascript object become undefined on recordset

I have an acces database and I would like to import data to javascript.
This is my code:
function Flight(){
this.number;
this.day;
this.updateDate;
this.html;
}
var dbPath = "mypath\\flight_bdd.mdb";
var flights = [];
function executeRequest(request){
//get datas
var adoConn = new ActiveXObject("ADODB.Connection");
var adoCmd = new ActiveXObject("ADODB.Command");
adoConn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + dbPath + "'");
adoCmd.ActiveConnection = adoConn;
var adOpenDynamic=2;
var adLockOptimistic=3;
var rs = new ActiveXObject("ADODB.Recordset");
rs.open(request, adoConn, adOpenDynamic, adLockOptimistic);
return rs;
}
function loadFlightsFromDatabase(){
//get datas
var rs = executeRequest("SELECT * FROM flight_data");
//empty flight array
flights = [];
//create flights
var i = 0
while(!rs.eof){
flights[i] = new Flight();
//set flight data
flights[i].number = rs.fields("flight_number");
console.log(flights[i].number);
rs.MoveNext();
console.log(flights[i].number);
i++;
}
}
The first console output returns the flight number and the second one returne undefined.
I think the value of the recordset is updated in my object when I have a move next, is there a way to prevent it ?
I think your connection goes out of scope and is getting closed. Try creating a disconnected recordset:
var adOpenStatic = 3;
var adUseClient = 3;
var adLockBatchOptimistic = 4;
var rs = new ActiveXObject("ADODB.Recordset");
rs.CursorLocation = adUseClient;
rs.open(request, adoConn, adOpenStatic, adLockBatchOptimistic);
rs.ActiveConnection = null;
adoConn.Close;
return rs;
But that said, rs.MoveNext(); should not affect already assigned property of your object (unless it's a reference type). What type is .number - can u show structure of Flight?
I find a solution,
I I concatenate my recordset
flights[i].number = rs.fields("flight_number") + "";
it works !!

Categories