Trouble accessing javascript property - javascript

I have an object called users inside a global object called streams. Each property of users is a username with the value of an array that stores other objects with info about each user. The project is supposed to be a small version of twitter. E.g:
var users = {};
users.bill = []
users.keith = [];
var someInfo = {};
someInfo.tweet = "Hello, I am a message";
someInfo.dateCreated = new Date();
users.keith.push(someInfo);
The above is in a separate .js file that is included in my index.html file. My index.html file also has a script section and that is where my problem lies. What I am attempting to do is retrieve the string from the tweet property, when a username is clicked on, using jQuery. Here is what I am trying.
var showTimeline = function (){
var tweeter = $(this).text(); // get username from whichever name is clicked on
console.log(tweeter); // log name to console. e.g tweeter holds "keith"
console.log(streams.users["keith"][0].message); // this works fine and extracts string as expected
console.log(streams.users[tweeter][0].message); // program breaks here and says "tweeter is undefined", right after i logged it to the console and showed it holds the string "keith"
};
jsfiddle

There are some invisible character(s) causing problems:
console.log(tweeter == 'douglascalhoun'); //false
This solves it:
var tweeter = $.trim($(this).text());
http://jsfiddle.net/26gwz/

Related

NEWBIE: Impossible to get my attached pdf in a mail with google script and form

I'm new to google script and I'm going crazy trying to do a simple tool.
I created a simple google form with just an email and a file uploader and I need just to insert an email and a pdf, and this should go to the recipient well HTML formatted and whit the pdf attached.
I'm new to this and I tried litterally every syntax using mailApp and Gmail app and the mail comes smooth but the pdf wont.
I know it's just a newbie stupid thing but I can't figure it out at my 74th attempt.
here's the code, I will be grateful forever with someone who can help me!
function sendPDF (e) {
var html = HtmlService.createTemplateFromFile("emailbolladireso.html");
var htmlText = html.evaluate().getContent();
var emailTo = e.response.getRespondentEmail();
var Subject = "---."
var textbody = "---."
var attach = e.response.getItemResponses();
var options = { htmlBody: htmlText};
if(emailTo !== undefined){
GmailApp.sendEmail(emailTo, Subject, textbody, options, )
attachments: attach[1];
}
}
First you have to get the id of your file wich is uploaded by your form to google drive.
You tried with:
var attach = e.response.getItemResponses();
But this will return you an array of objects with all your answers of your form.
From this object you have to extract the id of the uploaded PDF.
If you know the position, for example the first question in your form is for the pdf you can access it with attach[0] if it is e.g. in second position with attach[1], cause arrays index start with 0.
(You could look it also up with a for loop check for the name of the object.
attach[0].getItem().getTitle()
)
With attach[0] you get the next object and from this you get with attach[0].getResponse() finaly the id of your PDF.
attach[0].getResponse()
Now you "load" the file with the given id from google Drive (Make sure you have the permissions for access GoogleDrive)
var file = DriveApp.getFileById(attach[0].getResponse())
You can now attach your file (blob) to your attachments with the right MimeType
attachments: [file.getAs(MimeType.PDF)]
You should also place the attachments in the options of your email.
function sendPDF (e) {
var html = HtmlService.createTemplateFromFile("emailbolladireso.html");
var htmlText = html.evaluate().getContent();
var emailTo = e.response.getRespondentEmail();
var Subject = "Form with PDF"
var textbody = "Your PDF is attached."
var attach = e.response.getItemResponses();
var file = DriveApp.getFileById(attach[0].getResponse())
var options = { htmlBody: htmlText, attachments: [file.getAs(MimeType.PDF)]};
if(emailTo !== undefined){
GmailApp.sendEmail(emailTo, Subject, textbody, options);
}
}
Finaly it should work...
I tested it like this and it works for me.
DON'T PANIC!
Read also the docs -> https://developers.google.com/apps-script/reference/forms/item-response

Google Script - Adding images in document & removing copied files

I'm passing information from Google Sheets to a Document via Google Apps Script. All the information transfers with two exceptions...
The link of the picture shows rather than the image. How can I insert the image rather than the link?
In the folder it saves to, I get 2 versions of the document. One with the name I want, and another named 'Copy of Template'. I don't want the copy of the template, how can I either not create it, or delete it in the script?
Any help would be greatly appreciated.
function myFunction(e) {
var timestamp = e.values[0];
var studentName = e.values[1];
var firstName = e.values[2];
var studentNumber = e.values[3];
var dateOfBirth = e.values[4];
var studentImage = e.values[5];
var file = DriveApp.getFileById('fileId');
var folder = DriveApp.getFolderById('folderId')
var copy = file.makeCopy(studentName, folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{Time}}', timestamp);
body.replaceText('{{Name}}', studentName);
body.replaceText('{{Preferred Name}}', firstName);
body.replaceText('{{Student Number}}', studentNumber);
body.replaceText('{{DOB}}', dateOfBirth);
body.replaceText('{{Image}}', studentImage);
doc.saveAndClose();
}
The expected output is a document with relevant information, an image of the student, and only 1 version of the document in the folder.
I am unsure of why your code creates an extra copy of your file. This might be due to something else.
However, to change "{{image}}" to an image from an URL you can do this:
body.findText('{{Image}}').getElement().asParagraph()
.setText("") //Clears text
.appendInlineImage(UrlFetchApp.fetch(studentImage).getBlob()); //Adds image element from URL

Creating text files from array, using FS

I created an array of strings and placed them into an array called schoolsArray. I want to be able to create a text file for each school, using fs.
For some reason, I just can't get this to work. It seems that the issue is with using the value from schoolsArray[0] as a string in the path name. Please take a look at my series of tests. This first code snippet all works, but I added it just to help you understand that I import 'fs' and create a directory first.
Update - Added schoolArray creation per request
var fs = require('fs');
// Read all schools into array (read from text file)
const schoolFile = "./assets/dispatch/state/schools/county_name.txt";
fileInput = fs.readFileSync(schoolFile, "utf-8");
const schoolArray = fileInput.split("\n");
// Variable for chat logs directory
const chatDir = "./chat-logs";
// Create directory if it doesn't exist
if(!fs.existsSync(chatDir)){
fs.mkdirSync(chatDir);
}
The directory is created, now try make a file attempt #1
var schoolTextFile = chatDir + "/" + schoolArray[0] + ".txt";
fs.writeFileSync(schoolTextFile, "");
Uncaught Error: ENOENT: no such file or directory, open 'C:\Users\PC\Desktop\Node_Webkit_Test\chat-logs\Test School Name.txt'
at Object.fs.openSync (fs.js:653:18)
at Object.fs.writeFileSync (fs.js:1300:33)
Okay, so that doesn't work for some reason. Attempt #2 - I have come to think that the schoolArray[0] value isn't being read as a string, so I tried this:
var schoolTextFile = chatDir + "/" + toString(schoolArray[0]) + ".txt";
fs.writeFileSync(schoolTextFile, "");
There are no errors here, but the output is an undefined object:
Attempt #3 was to simply try a text string instead of using the value from my array. This worked exactly as intended.
var schoolTextFile = chatDir + "/" + "some Text 1234" + ".txt";
fs.writeFileSync(schoolTextFile, "");
Thus, the issue is pinpointed to be with the schoolArray[0] value being entered into the path. It seems silly to even test, but I did this anyway...
var somestring = "some text 1234";
console.log(typeof somestring);
// The log says that this is a string.
console.log(typeof schoolArray[0]);
// The log says that this is a string.
So then, why does one string work here, and the other causes path issues? Thanks in advance!
You must have some forbidden characters in schoolArray. Typically \r. Try
schoolArray = fileInput.split("\n").map( line => line.replace(/\r/g,''));

Adobe Javascript in Action Wizard vs a form button

I've been writing some javascript to fill in fields of a PDF form. I initially wrote the code in the "Action Wizard" in Adobe. I did not realize at the time that I was adding it to my local application, not the form itself. So I then copied it to a button on the from and now it is not working.
The code:
/* Test to read in a file and update the fields*/
var dataFrom = null;
//Grab the current path and update it to indicate the TempInfo location
var strPath = this.path;
strPath = strPath.slice(0,-12);
strPath = strPath + "TempInfo.txt"
//Get data from TempFile into array, display message if no file found
try{
var dataStream = util.readFileIntoStream(strPath);
var dataFrom = util.stringFromStream(dataStream);
}catch(e){
app.alert("Temp file not found");
}
//Put the data into an array and update the fields
var strTest = new Array();
strTest = dataFrom.split(/\n/);
getField("Username").value = strTest[0];
getField("UID").value = strTest[1];
//Clear the data
dataStream = null;
dataFrom = null;
strTest = null;
I am getting the app.alert "Temp file not found" so the "var dataStream = readFileInfoStream(strPath);" isn't reading in the file. I did app.alerts to verify the strPath variable has the right path and one to verify that dataStream is coming up null. Being that I copied it from the Action Wizard, I am unsure why its not working.
Just to make this a little odder (at least to me), if I open the JavaScript editor and highlight the code, it works fine.
For the util.readFileIntoStream method, when the cDIPath parameter is specified, the method can only be executed in a privileged context meaning during a batch, console event, or Action. It won't work when executed within the document context unless you create a Trusted Function.
Read this to understand how to executing privileged methods in a non-privileged context...
http://help.adobe.com/en_US/acrobat/acrobat_dc_sdk/2015/HTMLHelp/index.html#t=Acro12_MasterBook%2FJS_Dev_Contexts%2FExecuting_privileged_methods_in_a_non-privileged_context.htm&rhsearch=trusted%20function&rhsyns=%20

how to load data from text file to javascript array?

i have an array called items=["apple","mango","cherry"];
i wonder how i can load the array data from text file instead of declaring it?the text file data is stored like this "apple","mango","cherry",...
furthermore, how to add to the end of this this text file an item for example add "orange" after "cherry"?
items=["apple","mango","cherry"];
if (items.indexOf(myVariable2) == -1) {
// not found, so output it
t++;
document.myform3.outputtext3.value +=myVariable2+"\n";
}
With jQuery you can do something like this
$.get("textFile.txt", function(data) {
var items = data.split(',');
});
You may need something like this though
var items = data.replace(/"/g, '').split(',');
This is a start.
If this is a user input file then you may need to upload it before you work with it.
Sorry, but I don't believe it's quite that simple. Browsers restrict access to local drives (and to server drives) for security reasons.
But one way to access the text file using jQuery would be
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
var file = event.target.file;
var reader = new FileReader();
var txt=reader.readAsText(file);
var items=txt.split(",");

Categories