Populate SUM of column from accessdb into textbox using javascript - javascript

I have a webpage with a few textboxes; and an access database with columns that contain numeric data, dates and user id's.
I need help to SUM a column WHERE the date is >= 1/1/2013.
Lets just say i cant use server side scripting with my current setup. I need this done only by JS or jquery.
Here is the code i came up with to retrieve the sum. but the textbox is returned with this value "[object]".
Also, im not sure how to write the "WHERE" condition.
I'm sure its something simple im missing. any help will be greatly appreciated!!
function retrieve_records() {
var adoconn = new ActiveXobject("ADODB.Connection");
var adoRS = new ActiveXobject("ADODB.Recordset");
adoconn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='database.mdb'");
adoRS.Open("Select SUM(database_column_name) As Total FROM tablename", adoconn, 1, 3);
textbox1.value = adoRS;
adoRS.close();
adoconn.close();
}
Thanks!
Marvin.

This is cobbled to gether from a knowledge of ADO and Access rather than Javascript.
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = adoconn;
var strSQL = "Select SUM(database_column_name) As Total FROM tablename WHERE aDate=?";
cmd.CommandText = strSQL;
var param = cmd.CreateParameter("adate", 7, 1,, "2013/12/31");
cmd.Parameters.Append(param);
var adoRS = cmd.Execute();
textbox1.value = adoRS.Fields(0)
Fields(0) because you only have one field, Fields('Total') should also work. The date is a string above, it should work with Access, but you might like to use a proper date.

Related

ServiceNow - query table and insert incident

I m trying to implement a script that queries a table and checks for certain criteria.
If it is true then it will insert an incident.
I m not sure where this is going wrong, I am guessing it is the while loop.
I m new to scripting in servicenow if someone could assist.
Code is below
var kc = new GlideRecord('cmdb_ci_web_site');
kc.addQuery('owned_by', '=',
current.u_caller_id.sys_id).addOrCondition('u_secondary_site_owner', '=', current.user.sys_id);
kc.query();
While (kc.next())
{
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description ='Assign New User to PSO or SSO';
inc.u_category = 'KCCC';
inc.current.u_caller_id.sys_id.setDisplayValue();
inc.to_be_encrypted ='Assign New User to PSO or SSO';
inc.impact ='3';
inc.urgency = '3';
inc.insert();
}
This line is suspicious inc.current.u_caller_id.sys_id.setDisplayValue(); I would guess inc.current is undefined.
If that's still not working: I've had problems chaining the OR condition directly. Try setting a new variable for your OR condition:
var kc = new GlideRecord('cmdb_ci_web_site');
var kcOrCondition = kc.addQuery('owned_by', '=', current.u_caller_id.sys_id);
kcOrCondition.addOrCondition('u_secondary_site_owner', '=', current.user.sys_id);
kc.query();
Not really sure as to what you are trying to achieve with this line: inc.current.u_caller_id.sys_id.setDisplayValue();. Since caller_id is a reference field, you dont have to dot walk to it's sys_id to get the value, the system will automatically pick up the sys_id by default.
You can make changes to your script as:
var kc = new GlideRecord('cmdb_ci_web_site');
kc.addEncodedQuery('owned_by='+current.u_caller_id+'^OR u_secondary_site_owner='+current.user);
kc.query();
while (kc.next())
{
var inc = new GlideRecord('incident');
inc.initialize();
inc.setValue("short_description","Assign New User to PSO or SSO");
inc.setValue("u_category", "KCCC");
inc.setValue("to_be_encrypted", "Assign New User to PSO or SSO");
//inc.setValue(relevant_incident_field, current.u_caller_id);
inc.setValue("impact", "3");
inc.setValue("urgency", "3");
inc.insert();
}
Try changing this statement:
inc.current.u_caller_id.sys_id.setDisplayValue();
if you want to set a specific field in inc using the current value try this:
inc.somefieldininc = current.u_caller_id.sys_id;

Retrieve Google Sheets column by header name

Is there a way to retrieve a column dynamically by it's column name (header)?
Instead of:
var values = sheet.getRange("A:A").getValues();
Something like: (Just for simplicity)
var values = sheet.getRange(sheet.column.getHeader("name").getValues();
Please keep in mind that Google Apps Script is roughly ES3.
You can write one ;)
function getColValuesByName(sheet, name) {
var index = sheet.getRange(1,1,1,sheet.getLastColumn()).getValues()[0].indexOf(name);
index++;
return sheet.getRange(1,index,sheet.getLastRow(),1).getValues();
}
Here's a very simple one-line function you can copy. It returns the column number (A = 1, B = 2, etc.) for use in getRange, for example.
function getColByHeader(name) {
return SpreadsheetApp.getActiveSheet().getRange('1:1').getValues()[0].indexOf(name) + 1;
}
Although there is no direct way, there are plenty of ways to get what you want with a little set up:
Get all data and filter it(no set up):
var values = sheet.getDataRange().getValues();
var headers = values.splice(0,1);
headerIdx = headers[0].indexOf("name");
values = values.map(function(row){return [row[headerIdx]];})
Named ranges set up:
If you have named ranges associated with that column,
spreadsheet.getRangeByName('Sheet Name!name').getValues();//where 'name' is a named range
Developer metadata set up:
If you have developer metadata associated with that column,
SpreadsheetApp.getActive()
.createDeveloperMetadataFinder()
.withKey(/*METADATA_KEY_ASSOCIATED_WITH_COLUMN*/)
.find()[0]
.getLocation()
.getColumn()
.getValues();

how can i convert my data in javascript server side to json object and array?

i'm working with xpages and javascript server side i want to convert the fields in format json then i parse this dat and i put them in a grid,the problem is that these fields can contains values :one item or a list how can i convert them in json ?
this is my code :
this.getWFLog = function ()
{
var wfLoglines = [];
var line = "";
if (this.doc.hasItem (WF.LogActivityPS) == false) then
return ("");
var WFLogActivityPS = this.doc.getItem ("WF.LogActivityPS");
var WFActivityInPS = this.doc.getItem ("WFActivityInPS");
var WFActivityOutPS = this.doc.getItem ("WFActivityOutPS");
var WFLogDecisionPS = this.doc.getItem ("WF.LogDecisionPS");
var WFLogSubmitterPS = this.doc.getItem ("WF.LogSubmitterPS");
var WFLogCommentPS = this.doc.getItem ("WF.LogCommentPS");
var WFLogActivityDescPS = this.doc.getItem ("WF.LogActivityDescPS");
var Durr =((WFActivityOutPS-WFActivityInPS)/3600);
var json= {
"unid":"aa",
"Act":WFLogActivityPS,
"Fin":WFActivityOutPS,
"Durr":Durr,
"Decision":WFLogDecisionPS,
"Interv":WFLogSubmitterPS,
"Instruction":WFLogActivityDescPS,
"Comment":WFLogCommentPS
}
/*
*
* var wfdoc = new PSWorkflowDoc (document1, this);
histopry = wfdoc.getWFLog();
var getContact = JSON.parse(histopry );
*/ }
Careful. Your code is bleeding memory. Each Notes object you create (like the items) needs to be recycled after use calling .recycle().
There are a few ways you can go about it. The most radical would be to deploy the OpenNTF Domino API (ODA) which provides a handy document.toJson() function.
Less radical: create a helper bean and put code inside there. I would call a method with the document and an array of field names as parameter. This will allow you to loop through it.
Use the Json helper methods found in com.ibm.commons.util.io.json they will make sure all escaping is done properly. You need to decide if you really want arrays and objects mixed - especially if the same field can be one or the other in different documents. If you want them flat use item.getText(); otherwise use item.getValues() There's a good article by Jesse explaining more on JSON in XPages. Go check it out. Hope that helps.
If an input field contains several values that you want to transform into an array, use the split method :
var WFLogActivityPS = this.doc.getItem("WF.LogActivityPS").split(",")
// input : A,B,C --> result :["A","B","C"]

How to replace ' / ' with '-' inside ObservableArray ? Knockout js

Well i am trying to pass an observable array via ajax call to my controller but i get every value there except date . i get something like '01-01-01' etc .
I found the issue but unable to fix that as i dont know how to replace / with - .
My ObservableArray have around 10 list items each list item holds a many properties out of those startDate holds the date like ("23/10/2014") . i just need something like ("23-10-2014") .
Tought of posting my function's and more i hope thats not required in this case i believe .
Let me explain with bit of code and sample data :
function myarray()
{
var self=this;
self.startDate=ko.observable("");
self.name=ko.observable("");
self.place=ko.observable("");
}
MyObservableArray :
self.Main= ko.observableArray();
In between i do some stuff to load Data into self.Main and i am sending self.Main to controller having data like below :
self.Main[0] holds :
startDate() -->gives you "23/10/2014" //individual observables inside onservable array
name() --> "jhon"
place()--> "croatia"
Likely
self.Main[9] holds :
startDate() --> "29/05/2012"
name() --> "pop"
place()--> "usa"
I am trying like i want to alter the self.Main() and replace the startDate and use the same self.Main to send to my controller . Once after replacing in self.Main when i check date the / should be replaced with - .
Possible solution : i can use a different observable array and push all the VM's of Main into it but i am trying to do on self.Main without using other .
If someone can show some light it is much appreciated .
What I got that you are facing problem in escaping / in replace.
Try this
"(23/10/2014)".replace(/\//g,"-") //returns "(23-10-2014)"
I tried something for you using simple JS
var arr = [{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"}];
arr.forEach(function(obj){obj.date = obj.date.replace(/\//g,"-")});
console.log(arr) //will print date field as "(23-10-2014)" for all objects.
One solution would be to add a computed value that returns the array with the right values.
self.Main = ko.observableArray([...values here...]);
self.MainComputed = ko.computed(function() {
var computedArray = [];
self.Main().forEach(function(item) {
var newItem = myarray(); //Create a new item.
newItem.name(item.name());
newItem.place(item.place());
newItem.startDate(item.startDate().replace(/\//g,"-"));
computedArray.push(newItem);
});
return computedArray;
});
Then use the computed value in the places where you need the values with -.
I can think of two other ways to solve your issue, when taken into account that you want to use self.Main:
Replace the / with - before setting startDate on your item.
Change startDate to a computed value while storing the original value in another variable.
The first solution should be pretty straight forward (provided that it is a valid solution).
The second solution would look something like this:
function myarray()
{
var self=this;
self.originalStartDate = ko.observable("");
self.name = ko.observable("");
self.place = ko.observable("");
self.startDate = ko.computed(function() {
if(self.originalStartDate()) {
//We can only replace if the value is set.
return self.originalStartDate().replace(/\//g,"-");
}
else {
//If replace was not possible, we return the value as is.
return self.originalStartDate();
}
});
}
Now when you set the values you do something like:
var item = myarray();
item.originalStartDate = "01/01/2014";
Then when you get the value of startDate you would get "01-01-2014".
I haven't used Knockout.js but you can do this with a Javascript replace:
var str = [your array value] ;
var res = str.replace("/", "-");
For more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

doPost "unexpected error encountered" Web Form when submitting

I'm stuck on this web form after submitting. The below code worked in a previous web form I created with the help of Serge and a few others here some time ago. I'm attempting to re-purpose the code to make a PTO request web form. Right now, when submitting it spits out a "unexpected error encountered error and I'm lost on attempting to locate the issue. I'm thinking it may be how I've added panels together and their relationship? This is a work in progress, so i know clickhandlers will be added to provide response after submit etc. At the moment I'm looking to make sure it's passing entries in form to the spreadsheet. Thanks for any assistance.
//Setting the spreadshet ID and style of the form
var submissionSSkey = 'PUT YOUR KEY HERE'
var PanelStyle = {'background':'#c0d6e4','padding':'40px','borderStyle':'ridge','borderWidth':'15PX','borderColor':'#31698a'}
// Script-as-app template.
function doGet(e) {
//Creating the Appplication
var app = UiApp.createApplication();
//Creating panels to house the web form, instructional text, data pickers and setting style
var vertPanel = app.createVerticalPanel().setTitle('XYX Company PTO Request Form').setStyleAttributes(PanelStyle).setPixelSize(350,250);
var mainPanel = app.createFormPanel().setPixelSize(350,150);
var grid = app.createGrid(4,4).setId('ptogrid');
var ptoStart = app.createDateBox().setWidth('200').setName('ptoStartDate');
var ptoEnd = app.createDateBox().setWidth('200').setName('ptoEndDate');
var submitButton = app.createSubmitButton('<B>Submit</B>');
//Assigning widgets to the grid for positioning
grid.setText(1, 0, 'PTO Start Date')
.setWidget(1, 1, ptoStart)
.setText(2, 0, "PTO End Date")
.setWidget(2, 1, ptoEnd)
.setText(3, 0, '')
.setWidget(3, 1, submitButton)
//Instructions for completion of the PTO form by users.
vertPanel.add(app.createHTML("<b>PTO Request Form</b>"));
vertPanel.add(mainPanel);
vertPanel.add(app.createHTML("<br><b>Instructions:</b></br>" +
"<p>Select the starting date and the ending date for your PTO request. "+
"If you are taking a single day of PTO enter the starting and ending date as the same date. "+
"Click Submit once you've enter the dates. A request will be sent to your manager for reivew / approval.</p>"));
//Grabbing active users session information in order to look up user group assignment and manager
var employee = Session.getActiveUser().getEmail();
//Uses the UserManager class to get info by passing in the getActive user from base class
var userFirst = UserManager.getUser(Session.getActiveUser()).getGivenName();
var userLast = UserManager.getUser(Session.getActiveUser()).getFamilyName();
var wholeName = userFirst +" "+ userLast;
mainPanel.add(grid);
app.add(vertPanel);
return app;
}
function doPost(e) {
var app = UiApp.getActiveApplication();
var ptoStart = e.parameter.ptoStartDate;
var ptoEnd = e.parameter.ptoEndDate;
//var wholeName = e.parameter;
var timeStamp = new Date();
//Access spreadsheet store values
var sheet = SpreadsheetApp.openById(submissionSSkey).getSheetByName('PTO Requests');
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 11).setValues([[timeStamp,ptoStart,ptoEnd]]);
app.close();
return app;
}
I'm pretty sure the error comes from the spreadsheet ID, the sheet name or the range definition, please double check these parameters and see if it solves the issue.
I checked on my account with wrong values and it generated the same issue you have, it works as expected with correct values.
Edit: your comment seems to confirm that...( didn't see it when I answered...)
Note: the error was easy to find by looking at the execution transcript in the script editor UI, it would even give you the line of code where the error occured.

Categories

Resources