Below is my indexeddb(IDB) objectStore name and its calling method.
What I want is get the values from objectStore and based on condition matched values add those values calculation into Variable.
var item_id = [];
var db;
function displayNotes(filter) {
var line = 0;
var transaction = db.transaction(["frp_item_master"], "readonly");
var itemsname =[];
var itemsqty =[];
var itemsprice =[];
var itemsdisc =[];
var itemstax =[];
var handleResult = function(event) {
var cursor = event.target.result;
var price_with_tax;
var i = 0;
i++;
if (cursor) {
++line;
if (cursor.value.item_id == 20008)
{
item_id.push(event.target.result.value.item_id);
//and other array push here
//call function
price_with_tax = (get_tax(itemstax)/100)*itemsprice;
}
cursor.continue();
}
else {
//error
}
};
Then after creating my function which is called in above method.
function get_tax(p_tax_master_id){
var get_me;
var total_tax_rate = 0;
var transaction = db.transaction(["frp_tax_master"], "readonly");
var objectStore = transaction.objectStore('frp_tax_master');
objectStore.openCursor().onsuccess = function(event){
var cur = event.target.result;
get_me = event.target.result.value.tax_master_id;
console.log('get_me'+get_me);
if (cur) {
if (get_me == 2008)
{
total_tax_rate += event.target.result.value.rate;
console.log("total tax"+total_tax_rate);
}
cur.continue();
}
else {
console.log('else'+get_me);
}
};
return total_tax_rate;
};
I am getting errors as shown in images. Cursor is still running even if there no value into the object store and it shows Value can not be set to null.
Can we just loop through all records and till last values are fetched then exit from cursor assign that values to the variable.
Basically I am adding some number to a variable.
screenshot-1
screenshot-2
In this line you get the cursor:
var cur = event.target.result;
And here you correctly check that the cursor is not null before using it:
if (cur) {
But this line assumes that event.target.result is not null:
get_me = event.target.result.value.tax_master_id;
So when the cursor hits the end of its range, event.target.result is null which gives you the "can't read property 'value' of null" error on the exact line the console is telling you.
Consider moving that line into the if (cur) block.
In addition to what Joshua said, the onsuccess method is asynchronous, so your get_tax function will always return 0.
Consider something like:
function get_tax(p_tax_master_id, cb) {
var get_me;
var total_tax_rate = 0;
var transaction = db.transaction(["frp_tax_master"], "readonly");
var objectStore = transaction.objectStore('frp_tax_master');
objectStore.openCursor().onsuccess = function(event){
var cur = event.target.result;
console.log('get_me'+get_me);
if (cur) {
get_me = event.target.result.value.tax_master_id;
if (get_me == 2008) {
total_tax_rate += event.target.result.value.rate;
console.log("total tax"+total_tax_rate);
}
cur.continue();
} else {
console.log('else'+get_me);
cb(null, total_tax_rate);
}
};
};
You might also prefer to use a library such as ZangoDB so you could perform a query like:
var db = new zango.Db('db_name', ['frp_tax_master']);
var frp_tax_master = db.collection('frp_tax_master');
function get_tax(p_tax_master_id, cb) {
frp_tax_master.find({
tax_master_id: 2008
}).group({
total_tax_rate: { $sum: '$rate' }
}).toArray((error, docs) => {
if (error || !docs[0]) { cb(error); }
else { cb(null, docs[0].total_tax_rate); }
});
}
Related
I have a web app with one drop down list and 2 buttons. The drop down list get values from a sheet. The buttons write back in the sheet. The script I have works fine with that:
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(opt)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<opt.length;i++)
{
select.options[i] = new Option(opt[i],opt[i]);
}
}
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
}
}
document.getElementById("but1").addEventListener("click",listS);
function yourCallBack(response) {
}
</script>
In Java script:
function getSelectOptions()
{
var ss=SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh=ss.getSheetByName('Database');
var rg=sh.getRange(2,1,sh.getLastRow()-1,8);
var vA=rg.getValues();
var useremail = Session.getActiveUser().getEmail();
var opt=[];
for(var i=0;i<vA.length;i++)
{
if(vA[i][1] == "Pending Approval"){
if(vA[i][7]+"#xxx.com" == useremail || vA[i][7]+"#xxx.com" == useremail) {
opt.push(vA[i][3]+" REQ ID: "+vA[i][0]);
}
}
};
if (opt.length == 0) {opt.push("You do not have pending requests")};
return opt;
}
function doGet() {
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
}
function yourServerSideFunc(body) {
var value = body["value"];
var ss = SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh = ss.getSheetByName('Database');
var rg=sh.getRange(1,1,sh.getLastRow()-1,4);
var vA=rg.getValues();
var str = "Approved";
for(var i=0;i<vA.length;i++)
{
if(vA[i][3]+" REQ ID: "+vA[i][0] == value) {
sh.getRange(i+1, 2).setValue(str);
}
};
return ContentService.createTextOutput(JSON.stringify({message: "ok"})).setMimeType(ContentService.MimeType.JSON);
Now I am trying to regenerate the drop down list values after the button is clicked. I tried to add
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
in yourServerSideFunc(body) function to regenerate the HTML but does not work. I have tried to force a HTML refresh, but also did not work.
How can I easily re-trigger the generation of the drop down list items? Worst case scenario it is ok to refresh the whole page, but it should be simple to regenerate the drop down list since I have already the code for it.
I ended up with this work around.
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
//ADDED:
var select = document.getElementById("sel1");
select.options[index] = new Option("Approved! Please refresh","Approved! Please refresh");
selectElem.selectedIndex = index;
}
}
It does not really meet the original goal to refresh the list from the sheet. It would be great if someone else posted a solution to call the server function. I tried to add google.script.run.doGet() and similar, but it seems that it does not call the server side functions properly.
Hi I am using exceljs with JavaScript for my project but all of the variable that I modify within the readFile function are not changing outside scope.
//array for pdm paths
var arrFundPartyRole = [];
//mapping UI_id -> UI_Label
var labelUIMap = new Map();
//xlsx parsing to get necessary data
var workbook = new Excel.Workbook();
workbook.xlsx.readFile('Veritas_Full_082819.xlsx')
.then(function() {
//getting the worksheet and necessary columns
var worksheet = workbook.getWorksheet('VT_FULL');
var pdmPath = worksheet.getColumn(18);
var idUI = worksheet.getColumn(24);
var labelUI = worksheet.getColumn(27);
//iterate over all pdm paths by column
pdmPath.eachCell(function(cell, rowNumber) {
var path = cell.value;
if (path != null) {
//splitting the path
var pathElts = path.split(".");
if (pathElts[0] == 'FundPartyRole') {
arrFundPartyRole.push(pathElts);
}
}
});
//iterate over the UI_id column and find corresponding label
//counter to skip the first 2 columns?
var counter = 0;
idUI.eachCell(function(cell, rowNumber) {
if ((cell.value != null) && (counter > 1)) {
var idAddress = cell.address;
//address of id can be used to create address of label
var labelAddress = idAddress.replace("X", "AA");
var label = worksheet.getCell(labelAddress).value;
labelUIMap.set(cell.value, label);
}
counter = counter + 1;
});
/*for (i = 0; i < arrFundPartyRole.length; i++) {
if labelUIMap.get()
}*/
console.log(labelUIMap);
});
console.log(labelUIMap);
In this case, labelUIMap and arrFundPartyRole are blank when I print them outside scope but populated within the scope. Am I missing something?
You have to add after the first console.log(labelUIMap):
var i = last row that you have modify: number;
worksheet.getRow(i).commit();
workbook.xlsx.writeFile('Veritas_Full_082819.xlsx').then(()=>{
}).catch((err)=>{
throw err;
});
I am working with IndexedDB and I have a database with about 4000 records. I am trying to load small chucks of records at a time. Something similar to the infinite scrolling you see on your twitter feed. I've tried to Google this and found no code examples, but came across the advance method. I tried to use that, but still no success. The browser loaded all the records at once. How do I make it so I am only loading small amounts of records at a time?
var openRequest = indexedDB.open("USA", 1);
openRequest.onsuccess = function (e) {
var db = e.target.result;
var transaction = db.transaction(["Male"], "readonly");
var objectStore = transaction.objectStore("Male");
var cursor = objectStore.openCursor();
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
res.advance(25);
res.continue();
console.log(res.value);
}
}
}
The res.advance(25) will skip 25 rows but it will still load the rest. I changed your code + added some comments. You might want to use something like this:
var openRequest = indexedDB.open("USA", 1);
openRequest.onsuccess = function (e) {
var db = e.target.result;
var transaction = db.transaction(["Male"], "readonly");
var objectStore = transaction.objectStore("Male");
var cursor = objectStore.openCursor();
var results = null; // variable to store the results
var startIndex = 25,
maxResults = 25;
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
if (!results) {
results = [];
// skip rows, but only the first time
res.advance(startIndex);
} else {
results.push(res.value)
// We don't have 25 results yet, continue to load a next one
if(results.length < maxResults) {
res.continue();
}
}
}
}
transaction.oncomplete = function() {
// maxResults loaded or maybe it was the last page so it might not be full
console.log(results);
}
}
The below example is a lot more simple and works with autoincrement, but the pages are only full when results aren't deleted (not full code, but it's all about the IDBKeyRange.bound(0, 25))
var cursor = objectStore.openCursor(IDBKeyRange.bound(0, 25));
var results = [];
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
results.push(res.value)
}
}
transaction.oncomplete = function() {
console.log(results);
}
I am trying to pass product into the find() function that contains a .toArray() anonymous function containing both error and array. Unfortunately this entire find() function runs within an iteration and only the first value goes in. How do I pass product to the callbacks?
var find = function(product,callbacks){
foos.find({
"foo": product.bars,
}).toArray(function (error, array) {
if(error){
callbacks.error(product,error);
} else if (array.length == 0) {
callbacks.none(product);
} else {
callbacks.exists(product);
}
});
}
Before this function i was processing products with forEach() then had this run in a callback within that. This was big trouble. Processed products with a regular for and now it works.
Old code
var products = function(data,callback){
products.forEach(function(product){
insert.product_id = product.id;
var variants = product.variants;
variants.forEach(function(variant){
insert.sku = variant.sku;
insert.variant_id = variant.id;
return callback(insert);
});
});
}
New code
var products = function(data){
var insert = [];
var products = data.products;
for(var pKey in products){
var product = products[pKey];
var variants = product.variants;
var set = {}
set.product_id = product.id;
for(var vKey in variants){
var variant = variants[vKey];
set.sku = variant.sku;
set.variant_id = variant.id;
insert.push(set);
}
}
return insert;
}
I want to sort results obtained from indexedDB.
Each record has structure {id, text, date} where 'id' is the keyPath.
I want to sort the results by date.
My current code is as below:
var trans = db.transaction(['msgs'], IDBTransaction.READ);
var store = trans.objectStore('msgs');
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound("");
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false){
return;
}
console.log(result.value);
result.continue();
};
Actually you have to index the date field in the msgs objectStore and open an index cursor on the objectStore.
var cursorRequest = store.index('date').openCursor(null, 'next'); // or prev
This will get the sorted result. That is how indexes are supposed to be used.
Here's the more efficient way suggested by Josh.
Supposing you created an index on "date":
// Use the literal "readonly" instead of IDBTransaction.READ, which is deprecated:
var trans = db.transaction(['msgs'], "readonly");
var store = trans.objectStore('msgs');
var index = store.index('date');
// Get everything in the store:
var cursorRequest = index.openCursor();
// It's the same as:
// var cursorRequest = index.openCursor(null, "next");
// Or, if you want a "descendent ordering":
// var cursorRequest = index.openCursor(null, "prev");
// Note that there's no need to define a key range if you want all the objects
var res = new Array();
cursorRequest.onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) {
res.push(cursor.value);
cursor.continue();
}
else {
//print res etc....
}
};
More on cursor direction here: http://www.w3.org/TR/IndexedDB/#cursor-concept
IDBIndex API is here: http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex
Thanks to zomg, hughfdjackson of javascript irc, I sorted the final array. Modified code as below:
var trans = db.transaction(['msgs'], IDBTransaction.READ);
var store = trans.objectStore('msgs');
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound("");
var cursorRequest = store.openCursor(keyRange);
var res = new Array();
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false){
**res.sort(function(a,b){return Number(a.date) - Number(b.date);});**
//print res etc....
return;
}
res.push(result.value);
result.continue();
};