is my if statement doing what i think its doing? - parse-platform

Here I have tis function that is querying data and returning it to me and im putting that data in to html elements to make a post.my if statement at the bottom is where im having a bit of problem i trying to only apply my comment window once to the new clones once they have been pushed over to the new div called story board, i believe im telling my if statement that if the class already exists in that new clone then do nothing else apply it there.. to seee what i am talking about...here is my test domain...http://subdomain.jason-c.com/
sign in is "kio" pass is the same and when you hit publish on the stories, everytime a nw one hits it will apply comment box to a post in the storyboard window that already has a comment text area. what am i doing wrong.
function publishWindowHandler(){
var query = new Parse.Query('Post');
console.log(currentUser);
query.equalTo("User", currentUser);
query.include("User");
query.descending("createdAt")
console.log(user.get('username'));
query.find({
success:function(results){
document.getElementById("publishCenter").textContent = "";
for(var i =0; i < results.length; i++){
var userPost = results[i];
//console.log(userPost.get("User") + " / " + userPost.get("Author") + " / " + userPost.get("Story") + " / " + userPost.get("objectId"));
var authorTitle = document.createElement("p");
var newPost = document.createElement("P");
var title = document.createElement("P");
var userLabel = document.createElement("p");
var postId = userPost.id;
var postBtn = document.createElement("INPUT");
postBtn.className ="publishBtn";
postBtn.id ="publishBtn";
postBtn.setAttribute("Type", "button");
postBtn.setAttribute("value", "Publish");
title.textContent = "Story: " + userPost.get("Title");
authorTitle.textContent = "Author: " + userPost.get("Author");
newPost.textContent = userPost.get("Story");
userLabel.textContent = "Published by: " +userPost.get("User").get ("username");
var postWrapper = document.createElement("DIV");
postWrapper.className = "postWrapper";
postWrapper.id = postId;
document.getElementById("publishCenter").appendChild(postWrapper);
postWrapper.appendChild(title);
postWrapper.appendChild(authorTitle);
postWrapper.appendChild(newPost);
postWrapper.appendChild(userLabel);
postWrapper.appendChild(postBtn);
postBtn.addEventListener("click", publicViewHandler);
function publicViewHandler(){
$(this).parent(".postWrapper").clone().appendTo(".storyBoard");
function testWindow(){
if($(publicBoard).children().hasClass(".commentWindow")){
}
else
{
$(".storyBoard").children().append(commentWindow);
}
}
testWindow();
}
}
}
})
}

According to the documentation, jquery hasClass doesn't need '.' prefixing the passed in class name.
https://api.jquery.com/hasclass/
Try removing that and see if that get's you anywhere.
Also, where is the variable commentWindow defined? Is it global?

var myClone = $(this).parent().clone(true);
myClone.appendTo(".storyBoard");
console.log(publicBoard);
console.log("hello",$(this));
console.log($(publicBoard).find('.postWrapper').find("commentWindow"));
myClone.append($(commentWindow).clone());
this is what i ended up doing to solve my issue took me a while and a little help from a friend.

Related

Get a list of keys returned from PFObject Javascript

I'm working on some cloud code right now where I have an id I query against which returns all the data for that row.
I then need to iterate over all the fields (columns) of data and make some changes to the values then update that row.
Im able to get the data from parse but im not sure how to pull out the PFObject keys to iterate over the data in a for loop , make changes then save.
Here is some sample code where I hardcoded a field value in but I'm not sure how to get the fields, then iterate over them in a for loop..
Also excuse the JS code, I its been years since I wrote any JS.
<script type="text/javascript">
Parse.initialize("xxxx", "xxxx");
var LocationTag = Parse.Object.extend("LocationTags");
var query = new Parse.Query(LocationTag);
query.equalTo("SomeId", "302d87f2-0188-4cbe-bc2c-e6dcbf822539");
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var data = object.get('T0fYiV9PeeU'); <--- hardcoded field key.. i need to iterate over all fields returned from the row..
count = data.length;
for (var c = 0; c < count; c++) {
var res = Number(data[c].split(":")[0]);
text += "Value: " + res + "<br>";
sum += parseInt(res);
}
document.getElementById("main").innerHTML = text + ' sum: ' + sum + ' average: ' + sum/100 + results
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
Any ideas.. sorry again if its just a simple JS issue.. but I need to iterate over all fields, returned in the PFObject
If I understand correctly, you want a list of properties from a Parse.Object. The easiest way to to this is to call .toJSON() on the Parse.Object and then extract the keys from the json.
Example:
for (var i = 0; i < results.length; i++) {
var pfObject = results[i];
var jsonObject = pfObject.toJSON();
var pfKeys = [];
for(var key in pfKeys){
if(jsonObject.hasOwnProperty(key)){
pfKeys.push(key);
}
}
//Now we have a list of the pfObject keys in pfKeys
}

Need alternative to .makeCopy in Google Apps Script to decrease run time

I wrote a mail merge script that works great, but execution transcripts revealed that the .makeCopy task alone consumed 60% of the 6 minute run time. I am trying to re-write the script in a way that enables me to:
Open a document template
populate the body of the template with spreadsheet data
create a new document
copy the body of the populated template to the new document
save the new document as a PDF, attach it to an email and send it
delete the new document (I don't need to retain a copy)
At present, I am receiving a "TypeError" appendtoDoc is not a function, it is undefined." Error in line 72.
//Creates the custom menu in the spreadsheet "Run Script"
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Script')
.addItem('Create Certs', 'menuItem1')
.addToUi();
}
//Nest the createDocument function within the menuItem1 function for execution
function menuItem1() {
function createDocFromSheet() {
}
//Defines the start row and calculates the number of rows to be processed
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = Browser.inputBox("Enter Start Row");
var endRow = Browser.inputBox("Enter End Row");
var numRows = (endRow - startRow) + 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 7);
//defines the variables and the email body
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var date = row[0];
var nic = row[1];
var course = row[2];
var lastname = row[3];
var firstname = row[4];
var middle = row[5]
var email = row[6];
var docname = lastname+" "+nic+" PME Cert";
var subjectTxt = "NWC "+ course +" Online PME Course Certificate";
var fullBody = "PME COURSE COMPLETION CERTIFICATE" + "\n\n";
fullBody += "Your " + course + " course completion certificate is attached." + "\n\n";
fullBody += "Regards," + "\n\n";
fullBody += "Professor Steve Pierce" + "\n";
fullBody += "U.S. Naval War College "+ "\n";
fullBody += "Online PME Program Team" + "\n\n";
fullBody += "Learn more about NWC's Online PME Program at the link below:" + "\n";
fullBody += "http://www.usnwc.edu/Academics/College-of-Distance-Education/PME-(1).aspx" + "\n";
// The old makeCopy code
// var docId = DriveApp
// .getFileById("1CjdoldpJmPskkqStpmBk3dRznFyURgY5mMsfVHfIGz4")
// .makeCopy(docname).getId();
// Open the document template
//function createDocFromSheet(){
var templateid = "1CjdoldpJmPskkqStpmBk3dRznFyURgY5mMsfVHfIGz4"
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
//create the new document
var newDoc = DocumentApp.create(lastname+" "+nic+" PME Cert");
var newDocId = newDoc.getId()
var file = DriveApp.getFileById(newDocId)
// fill in the template with data
for (var i in data){
var row = data[i];
// opens the template and populates it with data from the sheet
var docid = DriveApp.getFileById(templateid).getId();
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
body.replaceText('fname', firstname);
body.replaceText('lname', lastname);
body.replaceText('midname', middle);
body.replaceText('course', course);
body.replaceText('date', date);
doc.saveAndClose();
// appends data from the template to the new document
var body = doc.getActiveSection();
var newBody = newDoc.getActiveSection();
appendToDoc(body, newBody);
DocsList.getFileById(docid).setTrashed(true); //deletes the temp file
}
}
function appendToDoc(src, dst) {
for (var i = 0; i < src.getNumChildren(); i++) {
appendElementToDoc (dst, src.getChild(i));
}
}
function appendElementToDoc (doc, object) {
var type = object.getType();
var element = object.copy();
if (type == DocumentApp.ElementType.PARAGRAPH) {
if (element.asParagraph().getNumChildren() != 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) {
var blob = element.asParagraph().getChild(0).asInlineImage().getBlob();
doc.appendImage(blob);
}
else doc.appendParagraph(element.asParagraph());
}
MailApp.sendEmail(email, subjectTxt, fullBody, {attachments: Newdoc.getAs("application/pdf")});
SpreadsheetApp.flush ();
DriveApp.getFileById(docId).setTrashed(true);
}}}
I modified your script to do it differently: I took a template, did replaceText then created a pdf from the changed template and sent the email; then I did replaceText again, pdf, email etc etc. I could email 10 certs in 15 secs this way. I didn't try a bigger number, and didn't check for errors.
function creatCertPdfAndEmail() {
var sheet = SpreadsheetApp.openById('1fDe0ju0zkDr0cdA5hWBC4RsxZgFv6mIFn6W1WU-0S0w').getSheets()[0]; //I created a separate spreadsheet for testing purposes.
var startRow =2;
var endRow =10 ;
var numRows = (endRow - startRow) + 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 7);
var counter =0;
var data = dataRange.getValues();
var templateid = "1DizlNa2ENpEMTUGhM78J0ozgh8A8Sc9fI1q1XmhvuLk"
var docid = DriveApp.getFileById(templateid).getId();
var dateOld;
var courseOld;
var allTheNameOld;
for (var i = 0; i < data.length; ++i) {
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
var row = data[i];
var date = new Date().getTime() - new Date(row[0]).getTime(); //like this for testing to get a different value on each pdf
var nic = row[1];
var course = row[2];
var lastname = row[3];
var firstname = row[4];
var middle = row[5]
var email = row[6];
// var docname = lastname+" "+nic+" PME Cert"; //not used in this version
var subjectTxt = "NWC "+ course +" Online PME Course Certificate";
var fullBody = "PME COURSE COMPLETION CERTIFICATE" + "\n\n";
fullBody += "Your " + course + " course completion certificate is attached." + "\n\n";
fullBody += "Regards," + "\n\n";
fullBody += "Professor Steve Pierce" + "\n";
fullBody += "U.S. Naval War College "+ "\n";
fullBody += "Online PME Program Team" + "\n\n";
fullBody += "Learn more about NWC's Online PME Program at the link below:" + "\n";
fullBody += "http://www.usnwc.edu/Academics/College-of-Distance-Education/PME-(1).aspx"
+ "\n";
var row = data[i];
var allTheName = firstname+' '+middle+' '+lastname
if(counter ==0){
body.replaceText('allTheName',allTheName); // body.replaceText('Congratulations .*?\.',allTheName);
body.replaceText('coursex', course);
body.replaceText('datex', date);
}
else {
body.replaceText(allTheNameOld,allTheName);
body.replaceText(courseOld, course);
body.replaceText(dateOld, date);
}
dateOld = date;
courseOld = course;
allTheNameOld = allTheName
counter ++
doc.saveAndClose()
var attachment = doc.getAs("application/pdf")
MailApp.sendEmail(email, subjectTxt, fullBody, {attachments: attachment});
}
}
I tried to re-create your basic code structure in a simpler format, trying to reproduce the error.
//Nest the createDocument function within the menuItem1 function for execution
function menuItem1() {
function createDocFromSheet() {}
for (var i = 0; i < 2; ++i) {
//create the new document
Logger.log("First Loop ran i = " + i);
for (var i = 0; i < 2; ++i) {
Logger.log(' Inner For loop: i = ' + i)
appendToDoc();
}
}
function appendToDoc() {
Logger.log('appendToDoc ran!');
for (var i = 0; i < 2; ++i) {
Logger.log('appendToDoc For Loop i=' + i);
appendElementToDoc();
}
}
function appendElementToDoc() {
Logger.log('appendElementToDoc ran!');
Logger.log('');
}
}
That code actually runs for me, and is able to access the appendToDoc function when I run the menuItem1() function.
It looks like you have a function function createDocFromSheet() {} with nothing in it. I don't understand that.

Ace editor - It doesn´t change the error window dynamically

I have the next code:
var exeWindow = document.getElementById("exeWindow");
var errorWindow = document.getElementById("errorWindow");
var annot = editor.getSession().getAnnotations();
editor.getSession().on("changeAnnotation", execute);
function execute(){
exeWindow.innerHTML = eval(editor.getValue());
errorWindow.innerHTML = "";
annot = editor.getSession().getAnnotations();
for (var key in annot){
if (annot.hasOwnProperty(key))
console.log(annot[key].text + "on line " + " " + (parseInt(annot[key].row)+1));
errorWindow.innerHTML = annot[key].text + " Line " + " " + (parseInt(annot[key].row)+1);
exeWindow.innerHTML = "";
}
if (TogetherJS.running) {
TogetherJS.send({type: "execute"});
}
};
Im trying to capture the error logs, and before execute a valid code works, but once I introduce for example 2+2, despite of exeWindow changes correctly, if a rewrite it to 2+a for example, searching a new error, the exeWindow doesn´t changes and the error does not appears in errorWindow.
EDIT: Sorry, the problem is that is not getting the correct errors, only the errors like 'missing semicolon'.
If someone is interested, the solution I found is the next one:
function execute(){
try {
exeWindow.innerHTML = eval(editor.getValue());
errorWindow.innerHTML = "";
} catch(err){
var annot = editor.getSession().getAnnotations();
for (var key in annot){
if (annot.hasOwnProperty(key)){
errorWindow.innerHTML = annot[key].text + " Line " + " " + (parseInt(annot[key].row)+1);
exeWindow.innerHTML = "";
}
}
}
if (TogetherJS.running) {
TogetherJS.send({type: "execute"});
}
};
Simple as that :)

How do I fix charset problems in .gs script?

I have a problem with charsets.
I parsed a csv file in google-app-engine and I'm posting to an uiapp table.
But I checked special characters like áéíóú and those are not well displayed (?square symbol).
When I was setting up my code I played writing the string imported to a google docs document and it worked the same.
some advice please?
I search for:
a global charset definition to the code. or
string var transformation that makes the chars appear like I want to. (avoiding html &number definitions.
Is this related to the blob object?
The thing is important i come from spain and we need such characters.
app that get's a csv ';' delimited file and shows it's content
I post all my code, it's barely as the tutorial that is given.
function arreglaUrl(cadena){
var texto = cadena[cadena.length - 2]
if (texto == ''){
cadena[cadena.length - 2] = 'Sin enlace';
}
else{
cadena[cadena.length - 2] = '<center>Link.</center>' ;
};
}
function parsedCSV(){
var listaArchivos = DocsList.getFolderById('XXXXX').getFiles()
for (var i = 0; i < listaArchivos.length; i++) {
if (listaArchivos[i].getName() == 'baul.csv'){
var origen = listaArchivos[i];
};
}
var texto = origen.getContentAsString();
var arra = Utilities.parseCsv(texto,";");
return(arra);
}
function doGet() {
var datos = parsedCSV()
var baul = Charts.newDataTable()
for (i = 0; i < datos[0].length; i++){
baul.addColumn(Charts.ColumnType.STRING, datos[0][i])
}
for (i = 1; i < datos.length; i++){
arreglaUrl(datos[i]) // this only makes some html i need to post some links
baul.addRow(datos[i])
}
baul.build();
var sectorFilter = Charts.newCategoryFilter()
.setFilterColumnLabel("sector")
.build();
var tipoFilter = Charts.newCategoryFilter()
.setFilterColumnLabel("tipo")
.build();
var searchFilter = Charts.newStringFilter()
.setFilterColumnLabel("Titulo")
.build();
var searchDesc = Charts.newStringFilter()
.setFilterColumnLabel("descripcion")
.build();
var tableChart = Charts.newTableChart().setOption('allowHtml', true).setDimensions(0,0)
.build();
var dashboard = Charts.newDashboardPanel()
.setDataTable(baul)
.bind([sectorFilter, tipoFilter, searchFilter, searchDesc], [tableChart])
.build();
var uiApp = UiApp.createApplication().setTitle('Baul de Recursos');
var anchoTotal = '100%';
dashboard.add(uiApp.createVerticalPanel()
.add(uiApp.createHorizontalPanel()
.add(sectorFilter)
.add(tipoFilter)
.setSpacing(15)
)
.add(uiApp.createHorizontalPanel()
.add(searchFilter)
.add(searchDesc)
.setSpacing(15)
)
.add(uiApp.createHorizontalPanel()
.add(tableChart).setBorderWidth(1).setHorizontalAlignment(UiApp.HorizontalAlignment.CENTER).setWidth(anchoTotal)
)
);
uiApp.add(dashboard);
return uiApp;
}
I found it, we need to get the content of the file first with a Blob object.
This function is the one I use to parse some csv info into an array:
function parsedCSV(){
//searching the file. This gets only one file in var origen
var listaArchivos = DocsList.getFolderById('XXXXXXX').getFiles()
for (var i = 0; i < listaArchivos.length; i++) {
if (listaArchivos[i].getName() == 'baul.csv'){
var origen = listaArchivos[i];
};
}
// HERE IS THE GOOD DEFINITION OF CHAR:
var texto2= origen.getBlob().getDataAsString('ISO-8859-1');
// I put all the corrected text in an array
var arra = Utilities.parseCsv(texto2,";");
return(arra);
}
This is the solved thing: https://script.google.com/macros/s/AKfycbyHa-bLWBHBr3qifbvzxecqGgGUYX8mhyo-TKoyfGvy/exec
The trick:
var textVariableName = fileObjectVariableName.getBlob().getDataAsString('ISO-8859-1');

What exactly am I sending through the parameters?

When doing a XMLHttpRequest and using POST as the form method, what exactly am I sending? I know it should be like send(parameters), parameters = "variable1=Hello", for example. But what if I want to do this:
parameters = "variable1=" + encodeURIComponent(document.getElementById("variable1").value);
variable1 being the id of the HTML form input.
Can I do it like this or do I need to assign the encodeURIComponent value to a javascript variable and send that variable:
var variable2;
parameters = "variable2=" + encodeURIComponent(document.getElementById("variable1").value);
You're suppose to send the object and it's value, but, is it an object from the HTML form, a javascript object or a php object? The problem is I already tried it and I still can't get the encoded input in my database, all I get is the raw input from the user.
BTW, I know it's a pretty dull question, but I feel the need to understand exactly what I'm doing if I want to come up with a solution.
g
function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
//INSERT
function insert()
{
var Faculty2 = encodeURIComponent(document.getElementById("Faculty").value);
var Major2 = encodeURIComponent(document.getElementById("Major").value);
var Professor2 = encodeURIComponent(document.getElementById("Professor").value);
var Lastname2 = encodeURIComponent(document.getElementById("Lastname").value);
var Course2 = encodeURIComponent(document.getElementById("Course").value);
var Comments2 = encodeURIComponent(document.getElementById("Comments").value);
var Grade2 = encodeURIComponent(document.getElementById("Grade").value);
var Redflag2 = encodeURIComponent(document.getElementById("Redflag").value);
var Owner2 = encodeURIComponent(document.getElementById("Owner").value);
//Location and parameters of data about to be sent are defined
//Required: verify that all fields are not empty. Use encode URI() to solve some issues about character encoding.
var params = "Faculty=" + Faculty2 + "&Major=" + Major2 + "&Professor=" + Professor2 + "&Lastname=" + Lastname2 + "&Course=" + Course2 + "&Comments=" + Comments2 + "&Grade=" + Grade2 + "&Redflag=" + Redflag2 + "&Owner=" + Owner2;
var url = "prehp/insert.php";
http.open("POST", url, true);
//Technical information about the data
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
//Now, we send the data
http.onreadystatechange = function()
{
if(http.readyState == 4)
{ var answer = http.responseText;
document.getElementById('insert_response').innerHTML = "Ready!" + answer;
}
else
{document.getElementById('insert_response').innerHTML = "Error";
}}
http.send(params);
}
PHP code:
$insertAccounts_sql = "INSERT INTO Information (Faculty, Major, Professor, Lastname, Course, Comments, Grade, Redflag, Owner)
VALUES('$_POST[Faculty]','$_POST[Major]','$_POST[Professor]','$_POST[Lastname]','$_POST[Course]','$_POST[Comments]','$_POST[Grade]','$_POST[Redflag]','$_POST[Owner]')";
$dbq = mysql_query($insertAccounts_sql, $dbc);
if($dbq)
{
print "1 record added: Works very well!";
}
else
if(!$dbq)
{
die('Error: ' . mysql_error());
}
$dbk = mysql_close($dbc);
if($dbk)
{
print "Database closed!";
}
else
if(!$dbk)
{
print "Database not closed!";
}
I did that but the value that the database got was the raw input and not the encoded input. I'm running out of ideas, don't know what else to try. Could it be the settings of the database, can the database be decoding the input before storing it? That seems far-fetched to me, but I've been looking at this from all angles and still can't come up with a fresh answer.
PS: Sorry for posting my comments on the answer area, first timer here.
when creating query strings, it has really nothing to do with objects or anything like that. All you want to be sending is key/value pairs. how you construct that is up to you, but it often neater and more manageable to assign your values to variables first. i.e.
var myVar1Value = encodeURIComponent(document.getElementById('variable1').value);
var myVar2Value = encodeURIComponent(document.getElementById('variable2').value);
var url = "http://www.mydomain.com?" + "var1=" + myVar1Value + "&var2=" + myVar2Value;
It's called a query string, so it's just a string. what you do with it on the server side is what makes the 'magic' happen.
edit: If you're having problems with values, then you should print them to console to verify you are getting what you expect.

Resources