Script works in IE but not Chromium - javascript

I have a script I am using in a html file my program accesses. it has been using IE as the browser, but the new version no longer uses IE, it uses Chromium. some of the script works, but it gets to a point that it does nothing. no errors just stops. I am guessing there is a difference in the way Chromium handles the script. The script is one I got online and modified. I will include the code below. I use the update option the most "AutomateExcel3" please ignore my code block outs and comments as I was trying to figure sometime else out.
thanks for the help
<script>
//*********************************************INTRODUCTION*****************************************
//When using Web.Link the first thing to do is initialize what's called a handle to Pro/Engineer
// Get Session, Model.
var mGlob = pfcCreate("MpfcCOMGlobal");
var oSession = mGlob.GetProESession();
var CurDwg = oSession.CurrentModel;
var CurWind = oSession.CurrentWindow;
var Base = "P:\ENGINEERING FILES\TPS PRE-PROD ENG\MV-22\excel_file.xls";
function UpdateControls(Opt)
{
bottom.innerHTML = "";
var Cntls="";
if (Opt==1)
{
Cntls = "<H2>To Export:</H2>"+
"<LI>Enter target Excel Files path</LI><LI>Pick \"Dwg Table\"</LI><LI>Pick Drawing Table</LI><P><INPUT id=FileName type=file size=80 value=\""+Base+"\"><BR>"+
"<INPUT id=button1 type=button value=\"Dwg Table\" onclick=\"AutomateExcel1()\">";
}
else if (Opt==2)
{
Cntls = "<H2>To Import:</H2>"+
"<LI>Enter the Excel Files path</LI><LI>Pick \"Next>>>\"</LI><LI>Pick Drawing To Place</LI><P><INPUT id=FileName type=file size=80 value=\""+Base+"\"><BR>"+
"<INPUT id=button1 type=button value=\"Next>>>\" onclick=\"AutomateExcel2()\">";
}
else if (Opt ==3)
{
Cntls = "<H2>To Update:</H2>"+
"<LI>Enter the Excel Files path</LI><LI>Pick \"Dwg Table\"</LI><LI>Pick Drawing Table</LI><P><INPUT id=FileName type=file size=80 value=\""+Base+"\"><BR>"+
"<INPUT id=button1 type=button value=\"Dwg Table\" onclick=\"AutomateExcel3()\">";
}
middle.innerHTML = Cntls;
}
function AutomateExcel1()
{
var MultipleLinesInCells = false;
//Have the user pick a table to export
var SelOptions = pfcCreate("pfcSelectionOptions").Create ("dwg_table");
SelOptions.MaxNumSels = 1;
var Selections = oSession.Select(SelOptions, null);
var Table = Selections.Item(0).SelItem;
//Build a matrix containing the values for the table
var nTableRows = Table.GetRowCount();
var nTableCols = Table.GetColumnCount();
//Start a new Excel Spreadsheet
var oXL;
oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
//Loop around the table and dump information to excel
for (i=0;i<nTableRows;i++)
{
for (j=0;j<nTableCols;j++)
{
var Cell = pfcCreate("pfcTableCell").Create(i+1, j+1);
var Mode = pfcCreate("pfcParamMode").DWGTABLE_NORMAL;
try
{
var Val = Table.GetText (Cell,Mode);
var Out="";
if (Val.Count>1)
MultipleLinesInCells = true;
for (k=0;k<Val.Count;k++)
{
if (k>0)
{
if (k<Val.Count)
{
Out = Out + " ";
}
}
Out = Out + Val.Item(k);
}
oSheet.Cells(i+1, j+1).Value = Out;
}
catch(er)
{
//Failure occurs when cells are merged, pro/e doesn't recognize cells that are now merged into another
}
}
}
//Bring up Excel for user to do with what they want.
//oXL.Visible = true;
oXL.UserControl = false;
if (FileName.value==null)
File = Base
else
File = FileName.value;
try
{
oWB.Close(true, File,null);
oXL.Workbooks.Close();
oXL.Quit();
Base = FileName.value;
var Out = "<H2>Success:</H2>Pick here for created document";
if (MultipleLinesInCells)
Out = Out + "<H2>Warning:</H2>The export resulted in some Multi-line cells being concatenated";
bottom.innerHTML = Out;
}
catch(er)
{
var Out = "<H2>Error:</H2>Could Not Write Specified File, please edit path and try again. If not Chuck Norris Might Get Angry!";
bottom.innerHTML = Out;
}
}
function AutomateExcel2()
{
//Have the user pick somewhere
var mousePick = oSession.UIGetNextMousePick ( pfcCreate("pfcMouseButton").MOUSE_BTN_LEFT);
var Orig = mousePick.Position;
//Start Excel
var oXL = new ActiveXObject("Excel.Application");
try
{
var oWB = oXL.Workbooks.Open(FileName.value);
var oSheet = oWB.ActiveSheet;
Base = FileName.value;
}
catch (er)
{
bottom.innerHTML = "<H2>Error:</H2>Could Not Open Specified File, \""+FileName.value+"\" for Import, please edit path and try again";
return;
}
//Start the table instructions
var TableInsts = pfcCreate("pfcTableCreateInstructions").Create (Orig);
var TableSizeType = pfcCreate("pfcTableSizeType").TABLESIZE_BY_NUM_CHARS;
TableInsts.SizeType = TableSizeType;
var columnInfo = pfcCreate ("pfcColumnCreateOptions");
//Look for headers in top row
var nCols=0;
var Val = oSheet.Cells(1,nCols+1).Value;
while (Val!=null)
{
nCols=nCols+1;
Val = oSheet.Cells(1,nCols+1).Value;
var column = pfcCreate ("pfcColumnCreateOption").Create (pfcCreate ("pfcColumnJustification").COL_JUSTIFY_LEFT,Math.round(oSheet.Cells(1,nCols).ColumnWidth+1));
columnInfo.Append (column);
}
//Push column information into Table Instructions
TableInsts.ColumnData = columnInfo;
//Push in the Header row
var rowInfo = pfcCreate ("realseq");
rowInfo.Append (2.0); //title line
TableInsts.RowHeights = rowInfo;
//Now create the table in proe
var CurTable = CurDwg.CreateTable(TableInsts);
//Populate the header information
for (var i=1;i<=nCols;i++)
{
var Val = oSheet.Cells(1,i).Value;
writeTextInCell (CurTable, 1, i, Val);
}
//Populate the rest of the table
var i=2;
var Row = oSheet.Cells(i,1).Value;
while (Row!=null)
{
CurTable.InsertRow (1.0, i-1, false);
for (var j=1;j<=nCols;j++)
{
var Val = oSheet.Cells(i,j).Value;
writeTextInCell (CurTable, i, j, Val);
}
i=i+1;
Row = oSheet.Cells(i,1).Value;
}
//Close down Excel.
oXL.UserControl = false;
oWB.Close(true);
oXL.Workbooks.Close();
oXL.Quit();
Excel.Application.Quit(); // added this to try to close excel
var Out = "<H2>Success:</H2>Excel sheet imported as Pro/E Drawing Table";
bottom.innerHTML = Out;
}
function AutomateExcel3()
{
//Have the user pick a table to update
var SelOptions = pfcCreate("pfcSelectionOptions").Create ("dwg_table");
SelOptions.MaxNumSels = 1;
var Selections = oSession.Select(SelOptions, null);
var Table = Selections.Item(0).SelItem;
//Start Excel
var oXL = new ActiveXObject("Excel.Application");
try
{
var oWB = oXL.Workbooks.Open(FileName.value);
var oSheet = oWB.ActiveSheet;
Base = FileName.value;
}
catch(er)
{
bottom.innerHTML = "<H2>Error:</H2>Could Not Open Specified File, \""+FileName.value+"\" for Update, please edit path and try again.";
return;
}
//Look for headers in top row and check them against the already existing headers
var nProCols = Table.GetColumnCount ();
var nCols=0;
var Val = oSheet.Cells(1,nCols+1).Value;
while (Val!=null)
{
nCols=nCols+2; // default was 1 changed to 2 now it doesn't delete the column if nothing in the first row.
//Check to see if we need to add another column
if (nCols>nProCols)
{
Table.InsertColumn (Math.round(oSheet.Cells(1,nCols).ColumnWidth+1), nCols-1, false);
nProCols=nProCols+1;
}
//Get current XL value
var ValXL = oSheet.Cells(1,nCols).Value;
//Get current ProE value
var cell = pfcCreate ("pfcTableCell").Create (1, nCols);
var mode = pfcCreate("pfcParamMode").DWGTABLE_NORMAL;
try
{
var ValProE = Table.GetText (cell, mode).Item(0);
}
catch(er)
{
var ValProE = "";
}
//Overwrite ProE value with XL value if they are not equal
if (ValProE!=ValXL)
{
ModifyCellText(Table, cell, ValXL);
}
Val = oSheet.Cells(1,nCols+1).Value;
}
//Check to see if any columns are left that need deleting off
//removed code and it appears to work without setting column to 15 above
while (nCols<nProCols)
{
Table.DeleteColumn (nProCols, false);
nProCols=nProCols-1; //default was -1 (changed to -0 and crashed creo)
}
//Populate the rest of the table
var nProRows = Table.GetRowCount();
var nRows = 0;
var Val = oSheet.Cells(nRows+1,1).Value;
while (Val!=null)
{
nRows = nRows + 1;
//Check to see if we need to add another row
if (nRows>nProRows)
{
Table.InsertRow (1, nRows-1, false);
nProRows=nProRows+1;
}
//Loop around all columns for each row
for (i=1;i<=nCols;i++)
{
//Get current XL value
var ValXL = oSheet.Cells(nRows,i).Value;
//Get current ProE value
var cell = pfcCreate ("pfcTableCell").Create (nRows, i);
var mode = pfcCreate("pfcParamMode").DWGTABLE_NORMAL;
try
{
var ValProE = Table.GetText (cell, mode).Item(0);
}
catch(er)
{
var ValProE = "";
}
//Overwrite ProE value with XL value if they are not equal
if (ValProE!=ValXL)
{
ModifyCellText(Table, cell, ValXL);
}
}
Val = oSheet.Cells(nRows+1,1).Value;
}
//Check to see if any rows are left that need deleting off
while (nRows<nProRows)
{
Table.DeleteRow (nProRows, false);
nProRows=nProRows-1;
}
CurDwg.Regenerate ();
//Close down Excel.
oXL.DisplayAlerts = false;
oXL.UserControl = false;
oWB.Close(true);
oXL.Workbooks.Close();
oXL.Quit();
// below code seams to stop excel instance created by from task manager while leaving other instances of excel alone
excel = null;
excelfile = null;
excelsheet = null;
CollectGarbage();
setTimeout("CollectGarbage()",1);
oSheet = null;
oWB = null;
oXL = null;
// below code kills excel from taskmanager but all excel is closed.
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("taskkill /F /IM EXCEL.exe");
CurDwg.UpdateTables ();
var Out = "<H2>Success:</H2>Excel sheet used as basis to update a Pro/E Drawing Table"+
"<p>Note:"+
"<LI>Cell Font and Alignment is Maintained for existing cells</LI>"+
"<LI>Rows can be added and removed - this is likely to require extra formatting</LI>"+
"<LI>There may be problems involving updating tables with merged cells</LI>"+
"<LI>Ensure you check the table for correct format after an update</LI>"+
"<LI>Congratulations Chuck Norris Approves!</LI>"+
"</p>";
bottom.innerHTML = Out;
}
function ModifyCellText(Table, cell, ValXL)
{
try
{
var CellNote = Table.GetCellNote (cell);
var CellNoteInsts = CellNote.GetInstructions (true);
var CellNoteTextLines = CellNoteInsts.TextLines;
var CellNoteTextLine1 = CellNoteInsts.TextLines.Item(0);
var CellNoteTextLine1Texts = CellNoteTextLine1.Texts;
var CellNoteTextLine1Text1 = CellNoteTextLine1Texts.Item(0);
var FontName = CellNoteTextLine1Text1.FontName;
}
catch(er)
{
var FontName = "ariallight.TTF";
}
var lines = pfcCreate("stringseq");
lines.Append (ValXL);
Table.SetText(cell, lines);
var CellNote = Table.GetCellNote (cell);
var CellNoteInsts = CellNote.GetInstructions (true);
var CellNoteTextLines = CellNoteInsts.TextLines;
var CellNoteTextLine1 = CellNoteInsts.TextLines.Item(0);
var CellNoteTextLine1Texts = CellNoteTextLine1.Texts;
var CellNoteTextLine1Text1 = CellNoteTextLine1Texts.Item(0);
//Switch Font
CellNoteTextLine1Text1.FontName = FontName;
CellNote.Modify (CellNoteInsts);
}
function writeTextInCell(table /* pfcTable */, row /* integer */,
col /* integer */, text /* string */)
{
var cell = pfcCreate ("pfcTableCell").Create (row, col);
var lines = pfcCreate ("stringseq");
lines.Append (text);
try{
table.SetText (cell, lines);
}
catch(er)
{
alert (row+" "+col);
}
}
// Function to create the activeX objects that are the interface to Web.Link.
function pfcCreate (className)
{
if (!pfcIsWindows())
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
if (pfcIsWindows())
return new ActiveXObject ("pfc."+className);
else
{
ret = Components.classes ["#ptc.com/pfc/" + className + ";1"].createInstance();
return ret;
}
}
//Checks what OS is being operated
//IE11 requires more indepth browser testing...
function get_browser_info(){
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
return {name:'IE',version:(tem[1]||'')};
}
if(M[1]==='Chrome'){
tem=ua.match(/\bOPR\/(\d+)/)
if(tem!=null) {return {name:'Opera', version:tem[1]};}
}
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
return {
name: M[0],
version: M[1]
};
}
function pfcIsWindows ()
{
var browser = get_browser_info();
if (browser.name.indexOf ("IE") != -1)
return true;
else
return false;
}
</script>
code worked perfectly in IE but not in the new browser I am forced to use

Related

Photoshop Scripting JavaScript loop through layers problem

I have a script that does the following:
loops through layers,
saves each layer in a separate folder (name of folder same as layer name)
saved layer images have names "nameofthedocument, nameofthelayer.png"
Now I wanted to add text item on top of those layers while they are saving as separate pngs so that for gods sake you don't have to always look at the file name but instead there would be text in the PNG image rasterized and says "nameofthelayer" variable.
So for each layer of course different text should be inserted in the image.
i encountered weird problems once I tried to do that what seamigly looked easy.
HEre is the link with a video and an explanation of the code as well as what I did and why it messed up the script.
https://drive.google.com/drive/folders/1h2KAiEuruLY_PQ2JVhQAwINDYPvk9xHS?usp=sharing
Thank you folks, please help me out
Code, image and video explanation is all available in the link
CODE:
// NAME:
// SaveLayers
// DESCRIPTION:
// Saves each layer in the active document to a PNG or JPG file named after the layer.
// These files will be created in the current document folder.
// REQUIRES:
// Adobe Photoshop CS2 or higher
// VERSIONS:
// 27 March 2013 by Robin Parmar (robin#robinparmar.com)
// preferences stored in object
// auto-increment file names to prevent collisions
// properly handles layer groups
// header added
// code comments added
// main() now has error catcher
// counts number of layers
// many little code improvements
// 26 Sept 2012 by Johannes on stackexchange
// original version
// enable double-clicking from Finder/Explorer (CS2 and higher)
#target photoshop
app.bringToFront();
//alert(activeDocument.name);
function main() {
// two quick checks
if(!okDocument()) {
alert("Document must be saved and be a layered PSD.");
return;
}
var len = activeDocument.layers.length;
// user preferences
prefs = new Object();
prefs.fileType = "";
prefs.fileQuality = 0;
prefs.filePath = app.activeDocument.path;
prefs.count = 0;
saveLayers(activeDocument);
//toggleVisibility(activeDocument);
}
function saveLayers(ref) {
var len = ref.layers.length;
// rename layers top to bottom
for (var i = 0; i < len; i++) {
var layer = ref.layers[i];
if (layer.typename == 'LayerSet') {
// recurse if current layer is a group
saveLayers(layer);
} else {
// otherwise make sure the layer is visible and save it
layer.visible = true;
saveImage(layer.name);
layer.visible = false;
}
}
}
function getNameWithoutExtension(nameWithExt) {
var nameWithoutExtension = nameWithExt;
return nameWithoutExtension.split(".")[0];
}
function saveImage(layerName) {
var f = new Folder("D:/Process/0/"+layerName);
f.create();
//////////////// BROKEN PART I ADDED
#target photoshop
// Current layer name as text layer
var myDoc = app.activeDocument;
var myRulers = app.preferences.rulerUnits
app.preferences.rulerUnits = Units.PIXELS;
var OriginalLayerName = myDoc.activeLayer.name
var myLayerName = myDoc.activeLayer.name + "text";
var myLayerText = myDoc.artLayers.add()
myLayerText.kind = LayerKind.TEXT
var myText = myLayerText.textItem
myColor = new SolidColor
myColor.rgb.red = 255
myColor.rgb.green = 0
myColor.rgb.blue = 0
myLayerText.textItem.color = myColor
myText.position = [0,20] // Upper Left
myText.justification = Justification.LEFT
myText.size = 12
myText.contents = myLayerName
myLayerText.name = myLayerName // Or add a fixed string in quotes i.e. 'My Great Layer Name!'
app.preferences.rulerUnits = myRulers
//////////////////////////////END OF THE BROKN PART
//var handle = generateName(f.path + "/",layerName, ".png");
//alert(handle);
var handle = getUniqueName(prefs.filePath + "/"+ layerName +"/"+ getNameWithoutExtension(activeDocument.name) + ", " + layerName);
//alert(handle);
prefs.count++;
if(prefs.fileType=="PNG") {
SavePNG(handle);
} else {
SaveJPEG(handle);
}
}
function getUniqueName(fileroot) {
// form a full file name
// if the file name exists, a numeric suffix will be added to disambiguate
var filename = fileroot;
for (var i=1; i<100; i++) {
var handle = File(filename + "." + prefs.fileType);
if(handle.exists) {
filename = fileroot + "-" + padder(i, 3);
} else {
return handle;
}
}
}
function padder(input, padLength) {
// pad the input with zeroes up to indicated length
var result = (new Array(padLength + 1 - input.toString().length)).join('0') + input;
return result;
}
function SavePNG(saveFile) {
pngSaveOptions = new PNGSaveOptions();
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
function SaveJPEG(saveFile) {
pngSaveOptions = new PNGSaveOptions();
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
// file type
var saveOpt = [];
saveOpt[0] = "PNG";
saveOpt[1] = "PNG";
// png type
var pngtypeOpt = [1];
pngtypeOpt[0]=24;
pngtypeOpt[1]=24;
function okDocument() {
// check that we have a valid document
if (!documents.length) return false;
var thisDoc = app.activeDocument;
var fileExt = decodeURI(thisDoc.name).replace(/^.*\./,'');
return fileExt.toLowerCase() == 'psd'
}
function wrapper() {
function showError(err) {
alert(err + ': on line ' + err.line, 'Script Error', true);
}
try {
// suspend history for CS3 or higher
if (parseInt(version, 10) >= 10) {
activeDocument.suspendHistory('Save Layers', 'main()');
} else {
main();
}
} catch(e) {
// report errors unless the user cancelled
if (e.number != 8007) showError(e);
}
}
function generateName(filePath, layerName, ext) {
var generatedName = app.activeDocument.name;
var generatedName = generatedName.split(".")[0];
generatedName = generatedName + ", " + layerName;
return filePath + generatedName + ext;
}
wrapper();

How to solve a problem time expired in javasrcipt

I am trying to send data to Google Sheet in my mobile application.
The data arrives well but the code does not return the result quickly
here is my JavaScript code.
The problem is that it takes a long time (around 360s) to return the result
it's ok
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/177kUZc61U8huVsq2OcGsiF2OGdPCSxMjkoh2C4KIWPM/edit#gid=0");
var sheet = ss.getSheetByName('Info');
function doGet(e) {
var action = e.parameter.action;
if (action == 'UpdateInfo') {
//return UpdateInfo(e);
}
}
function doPost(e) {
var action = e.parameter.action;
if (action == 'UpdateInfo') {
return UpdateInfo(e);
}
}
function UpdateInfo(e) {
var values = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
var email = e.parameter.email;
var password = e.parameter.password;
//var date = sheet.getRange('A').getValues();//new Date();
var name = e.parameter.name; ///Item1
var lname = e.parameter.lname;
var itemuserImage = e.parameter.itemuserImage;
var region = e.parameter.region;
var provaince = e.parameter.provaince;
var ecole = e.parameter.ecole;
var Unite = e.parameter.unite;
var niveau = e.parameter.niveau;
//var flag = 0;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var IDuser = sheet.getRange(i, 1).getValue();
//row[1];
var shetemail=sheet.getRange(i,2).getValue();
var shetpassword=sheet.getRange(i,3).getValue();
if (shetpassword==password && shetemail==email ) {
sheet.getRange(i,4).setValue(name);
// sheet.getRange(i,5).setValue(lname);
//row[2];
///zoydghnmayad sheet.getRange(i,7).setValue(region);
//row[4];
sheet.getRange(i,8).setValue(provaince);
//row[5];
sheet.getRange(i,9).setValue(ecole);
//row[5];
sheet.getRange(i,10).setValue(Unite);
//row[5];
sheet.getRange(i,11).setValue(niveau);
//row[5];
var dropbox="USERSIMAGE prof";
var folder, folders=DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder=folders.next();
} else {
folder=DriveApp.createFolder(dropbox);
}
var fileName=IDuser+"profile_pic.jpg";
var contentType="image/jpg" , bytes=Utilities.base64Decode(itemuserImage), blob=Utilities.newBlob(bytes, contentType,fileName);
var file=folder.createFile(blob);
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK,DriveApp.Permission.VIEW);
var fileIdumage=file.getId();
var fileUrlumage="https://drive.google.com/uc?export=view&id=" +fileIdumage; sheet.getRange(i,6).setValue(fileUrlumage);
//row[5];
return ContentService.createTextOutput("its ok").setMimeType(ContentService.MimeType.TEXT);
}
} ///thiya loop
}
Not quite sure.But do you check your image size of "profile_pic.jpg".
In my experience,if you capture the profile image using mobile app camera,the image size is extremely large.It will take ages to upload the image if you forget to compress it(no need such high HD image for profile, and compression is neccesary).
As a matter of that,please double check size of the image you were uploading.And please do not forget to compress it if it occupy too much space.

How to update all columns of a row at once using spreadsheet on Google Apps Script?

I read some other similar questions but I couldn't understand it how to do it on my code.
I have a spreadsheet that will be filled with an app, I am using appendRow to add rows but now I need to update the entire row with new array of data, if the variable pid(Código) from the row I am receiving exists on the spreadsheet, I need to update it, not add a new row.
function doGet(request) {
var sheet = SpreadsheetApp.openById("DOCUMENT_ID");
var data = sheet.getActiveSheet().getDataRange().getValues();
var updateIndex;
try{
var pid = request.parameter.pid;
var nome = request.parameter.nome;
var desc = request.parameter.desc;
var marca = request.parameter.marca;
var tipo = request.parameter.tipo;
var preco = request.parameter.preco;
var ativado = request.parameter.ativado;
var rowData = [pid, nome, desc, marca, tipo, preco, ativado];
// loop through all rows to check the column "pid" has the value of variable "pid"
for(var i = 1; i < data.length; i++){
if(data[i][0] == pid){
updateIndex = i;
}
}
// Update the row here with "rowData"?
sheet.
} catch(e){
console.log(e);
}
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType);
}
function doGet(request) {
var sheet=SpreadsheetApp.openById("DOCUMENT_ID");
var data=sheet.getActiveSheet().getDataRange().getValues();
var updateIndex;
try{
var pid=request.parameter.pid;
var nome=request.parameter.nome;
var desc=request.parameter.desc;
var marca=request.parameter.marca;
var tipo=request.parameter.tipo;
var preco=request.parameter.preco;
var ativado=request.parameter.ativado;
var rowData=[pid, nome, desc, marca, tipo, preco, ativado];
for(var i=1; i < data.length; i++){
if(data[i][0] == pid){
updateIndex=i;
break;
}
}
sheet.getRange(updateIndex+1,1,1,rowData.length).setValues([rowData]);
} catch(e){
console.log(e);
}
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType);
}
Sheet.getRange(start row,start col,number of rows,number of columns)
When pid is included in the values of the column "A", you want to replace the row with rowData.
When pid is NOT included in the values of the column "A", you want to append new row with rowData.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modified script:
When your script is modified, it becomes as follows.
function doGet(request) {
var sheet = SpreadsheetApp.openById("DOCUMENT_ID");
var range = sheet.getActiveSheet().getDataRange(); // Added
var data = range.getValues(); // Modified
var updateIndex = 0; // Modified
try{
var pid = request.parameter.pid;
var nome = request.parameter.nome;
var desc = request.parameter.desc;
var marca = request.parameter.marca;
var tipo = request.parameter.tipo;
var preco = request.parameter.preco;
var ativado = request.parameter.ativado;
var rowData = [pid, nome, desc, marca, tipo, preco, ativado];
for(var i = 1; i < data.length; i++){
if(data[i][0] == pid){
data[i] = rowData; // Added
updateIndex = i;
}
}
if (updateIndex != 0) { // Added
range.setValues(data);
} else {
sheet.appendRow(rowData);
}
} catch(e){
console.log(e);
}
// In your script, "result" is not declared. Please be careful this.
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType);
}
Note:
In your script, result is not declared. Please be careful this.
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to Web Apps. So please be careful this.
If I misunderstood your question and this was not the direction you want, I apologize.
My solution:
function doGet(request) {
// Modified
var sheet=SpreadsheetApp.openById("DOCUMENT_ID").getActiveSheet();
var data=sheet.getDataRange().getValues();
//
var updateIndex;
try{
var pid=request.parameter.pid;
var nome=request.parameter.nome;
var desc=request.parameter.desc;
var marca=request.parameter.marca;
var tipo=request.parameter.tipo;
var preco=request.parameter.preco;
var ativado=request.parameter.ativado;
var rowData=[pid, nome, desc, marca, tipo, preco, ativado];
for(var i=1; i < data.length; i++){
if(data[i][0] == pid){
updateIndex=i;
break;
}
}
// Modifed
sheet.getRange(updateIndex + 1, 1, 1, rowData.length).setValues( [rowData] );
//
} catch(e){
console.log(e);
}
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType);
}

TypeError: Cannot read property "length" from undefined variables

I have worked with code that pulls table information off a site and then places into Google Sheets. While this had worked great for months, it has come to my attention that is has randomly stopped working.
I am getting the message "TypeError: Cannot read property "length" from undefined." From code:
for (var c=0; c<current_adds_array.length; c++) {
I have done extensive searching but cannot come to conclusion as to what is wrong.
Full code seen here:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Get Data')
.addItem('Add new dispatch items','addNewThings')
.addToUi();
}
function addNewThings() {
// get page
var html = UrlFetchApp.fetch("#").getContentText();
// bypass google's new XmlService because html isn't well-formed
var doc = Xml.parse(html, true);
var bodyHtml = doc.html.body.toXmlString();
// but still use XmlService so we can use getDescendants() and getChild(), etc.
// see: https://developers.google.com/apps-script/reference/xml-service/
doc = XmlService.parse(bodyHtml);
var html = doc.getRootElement();
// a way to dig around
// Logger.log(doc.getRootElement().getChild('form').getChildren('table'));
// find and dig into table using getElementById and getElementsByTagName (by class fails)
var tablecontents = getElementById(html, 'formId:tableExUpdateId');
// we could dig deeper by tag name (next two lines)
// var tbodycontents = getElementsByTagName(tablecontents, 'tbody');
// var trcontents = getElementsByTagName(tbodycontents, 'tr');
// or just get it directly, since we know it's immediate children
var trcontents = tablecontents.getChild('tbody').getChildren('tr');
// create a nice little array to pass
var current_adds_array = Array();
// now let's iterate through them
for (var i=0; i<trcontents.length; i++) {
//Logger.log(trcontents[i].getDescendants());
// and grab all the spans
var trcontentsspan = getElementsByTagName(trcontents[i], 'span');
// if there's as many as expected, let's get values
if (trcontentsspan.length > 5) {
var call_num = trcontentsspan[0].getValue();
var call_time = trcontentsspan[1].getValue();
var rptd_location = trcontentsspan[2].getValue();
var rptd_district = trcontentsspan[3].getValue();
var call_nature = trcontentsspan[4].getValue();
var call_status = trcontentsspan[5].getValue();
//saveRow(call_num, call_time, rptd_location, rptd_district, call_nature, call_status);
current_adds_array.push(Array(call_num, call_time, rptd_location, rptd_district, call_nature, call_status));
}
}
saveRow(current_adds_array);
}
//doGet();
function saveRow(current_adds_array) {
// load in sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// find the current last row to make data range
var current_last_row = sheet.getLastRow();
var current_last_row_begin = current_last_row - 50;
if (current_last_row_begin < 1) current_last_row_begin = 1;
if (current_last_row < 1) current_last_row = 1;
//Logger.log("A"+current_last_row_begin+":F"+current_last_row);
var last_x_rows = sheet.getRange("A"+current_last_row_begin+":F"+current_last_row).getValues();
var call_num, call_time, rptd_location, rptd_district, call_nature, call_status;
// iterate through the current adds array
for (var c=0; c<current_adds_array.length; c++) {
call_num = current_adds_array[c][0];
call_time = current_adds_array[c][1];
rptd_location = current_adds_array[c][2];
rptd_district = current_adds_array[c][3];
call_nature = current_adds_array[c][4];
call_status = current_adds_array[c][5];
// find out if the ID is already there
var is_in_spreadsheet = false;
for (var i=0; i<last_x_rows.length; i++) {
//Logger.log(call_num+" == "+last_15_rows[i][0]);
if (call_num == last_x_rows[i][0] && call_time != last_x_rows[i][1]) is_in_spreadsheet = true;
}
Logger.log(is_in_spreadsheet);
//Logger.log(last_15_rows.length);
if (!is_in_spreadsheet) {
Logger.log("Adding "+call_num);
sheet.appendRow([call_num,call_time,rptd_location,rptd_district,call_nature,call_status]);
}
}
}
function getElementById(element, idToFind) {
var descendants = element.getDescendants();
for(i in descendants) {
var elt = descendants[i].asElement();
if( elt !=null) {
var id = elt.getAttribute('id');
if( id !=null && id.getValue()== idToFind) return elt;
}
}
}
function clearRange() {
//replace 'Sheet1' with your actual sheet name
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
sheet.getRange('A2:F').clearContent();}
function getElementsByTagName(element, tagName) {
var data = [];
var descendants = element.getDescendants();
for(i in descendants) {
var elt = descendants[i].asElement();
if( elt !=null && elt.getName()== tagName) data.push(elt);
}
return data;
}
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("C:C");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(/MKE$/, " Milwaukee, Wisconsin")];
}));
Please be careful when instantiating a new array. You are currently using var current_adds_array = Array(). You're not only missing the new keyword, but also, this constructor is intended to instantiate an Array with an Array-like object.
Try changing this to var current_adds_array = []

Compare value to another spreadsheet using array loop and write new values

Hello all I'm having trouble implementing array loops in my project... Here is what I want to do.
I have a spreadsheet called "Red Book" this sheet gets updated regularly once the staff have updated it I have a column where they can select to submit the data they've just entered on that specific row (editing this column calls an onEdit function).
The data will then be written to another spreadsheet (different file) called "Raw Data"
For each submit I have a unique identifier. I need the onEdit code to do the following...
Iterate through the column A to find the unique identifier
Once found update the data in columns 1 through 5
Below is the script I have so far:
function TransferToAppData(e) {
var destFile = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
var destSheet = destFile.getSheetByName("Raw App Data");
var ss = e.source;
var s = ss.getActiveSheet();
var uniConstRng = s.getRange("A1");
var uniqueConstVal = uniConstRng.getValue();
var NextOpenRow = destSheet.getLastRow() + 1;
var ActiveRow = e.range.getRow();
Logger.log(ActiveRow);
var uniqueVal = s.getRange(ActiveRow,1).getValue();
var add = s.getRange(ActiveRow,2).getValue();
var name = s.getRange(ActiveRow,3).getValue();
var dt = s.getRange(ActiveRow,5).getValue()
if (uniqueVal == "") {
s.getRange(ActiveRow,1).setValue(uniqueVal + 1);
uniConstRng.setValue(uniqueVal + 1);
var transferVals = s.getRange(ActiveRow,1,1,5).getValues();
Logger.log(transferVals);
destSheet.getRange(NextOpenRow,1,1,5).setValues(transferVals);
destSheet.getRange(NextOpenRow, 6).setValue("Applicant");
}
else {
var destLastRow = destSheet.getLastRow();
var destDataRng = destSheet.getRange(2,1,destLastRow,5)
var destValues = destDataRng.getValues();
var sourceValues = s.getRange(ActiveRow,1,1,5).getValues();
for( var i = 0; i < destValues.length; ++i){
if (destValues([i][0])==uniqueVal) {
for(n=0;n<destValues[0].length;++n){
///I"m stuck!!!
}
}
}
}
}
As you can see I have the first array loop going, but I'm having trouble figuring out how to do a second loop that iterates only on the row where the unique value is found and write the source data to ONLY to row where the unique value was found not the whole sheet.
I figured it out...
Below is the code and here is how it works...
When values in certain columns are edited this code is fired.
1--It finds the unique identifier located in the row which was edited.
2--Compares that identifier with a column of unique identifiers in another spreadsheet.
3--When a match is found it writes the change to the new spreadsheet and exits the loop
function TransferToAppData(e) {
var destFile = SpreadsheetApp.openById('1V3R2RnpA8yXmz_JDZSkBsK9tGR2LjHZp52p5I1CuQvw');
var destSheet = destFile.getSheetByName("Raw App Data");
var ss = e.source;
var s = ss.getActiveSheet();
var uniqueConstRng = s.getRange("A1");
var uniqueConstVal = uniqueConstRng.getValue();
var NextOpenRow = destSheet.getLastRow() + 1;
var ActiveRow = e.range.getRow();
var uniqueVal = s.getRange(ActiveRow,1).getValue();
if (s.getRange(ActiveRow,2).getValue() == "" || s.getRange(ActiveRow,3).getValue()=="" || s.getRange(ActiveRow,4).getValue()=="" || s.getRange(ActiveRow,5).getValue()=="") {
s.getRange(ActiveRow,13).clearContent();
Browser.msgBox("Address, Name, Date Entered & Rent are required fields!");
} else{
if (uniqueVal == "") {
s.getRange(ActiveRow,1).setValue(uniqueConstVal + 1);
uniqueConstRng.setValue(uniqueConstVal + 1);
var transferVals = s.getSheetValues(ActiveRow,1,1,5);
destSheet.getRange(NextOpenRow,1,1,5).setValues(transferVals);
destSheet.getRange(NextOpenRow, 6).setValue("Applicant");
}
else {
var destLastRow = destSheet.getLastRow();
var destValues = destSheet.getSheetValues(2,1,destLastRow,5);
var sourceValues = s.getSheetValues(ActiveRow,1,1,5);
for(var i = 0; i < destValues.length; ++i){
if (destValues[i][0]===uniqueVal) {
destSheet.getRange(i+2,1,1,5).setValues(sourceValues);
break;
}
}
}
s.sort(1,false);
destSheet.sort(1,false);
}
}

Categories

Resources