how to retrieve object from sqLite query? having problems - javascript

I am querying a local database and trying to retrieve my data in a form of array of objects to be able to manipulate them in another stage.
Below is my code and the scope I can access my object in and where I fail to access the object.
function setStageOneup(){
var teams = localStorage.teamsUp;
var tournament_id = 1;
var statement = "SELECT * FROM teams WHERE t_id= '"+tournament_id+"';";
localStorage.teamsUp = "";
var team_array = {};
var myTest = callBack(function(val){
var team = {};
for(var i = 0; i < val.rows.length; i++)
{
// teams_array[i]['id'] = val.rows.item(i).id
//console.log(val.rows.item(i).text)
team.id = val.rows.item(i).id;
team.t_id = val.rows.item(i).t_id;
team.m_t_id = val.rows.item(i).m_t_id;
team.name = val.rows.item(i).name;
team.weight = val.rows.item(i).weight;
team.goals = val.rows.item(i).goals;
team.win = val.rows.item(i).win;
team.draw = val.rows.item(i).draw;
team.lost = val.rows.item(i).lost;
team.misc = val.rows.item(i).misc;
team_array[i] = team;
console.log(team); // I am able to hee the output here
}
console.log(team_array); // I am able to hee the output here
},statement);
console.log(team_array); // I am unable to see here even though the variable is decleared in this scope
}
Thank you, if I missed anything please let me know.

Related

JSON-array and forEach issue

So... The problem I have according to the console is:
"Uncaught TypeError: Cannot read property 'title' of undefined
at custom.js:42, at Array.forEach (), at custom.js:39"
How is "title" undefined? What's wrong with my .forEach? (sad noises)
Example of first of six objects in the JSON-array I've built:
var newReleases = [
{
"title":"Honor - Defending the motherland",
"author":"Mark Thomas",
"genre":"Fiction",
"description":"In legislation and formal documents the suffix shire was generally not used: for example, Bedfordshire was referred to as the administrative county of Bedford and the Northamptonshire council as the county council of Northampton.The 1888 Act did not contain a list of administrative counties: it was not until 1933 and the passing of a new Local Government Act."},
For loop with forEach function:
for (var i = 0; i < 6; i++){
newReleases.forEach (function (newReleases) {
var bookTitle = document.getElementsByClassName('card-header')
var t = document.createTextNode(newReleases[i].title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')
var a = document.createTextNode(newReleases[i].authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle");
var genre = document.createTextNode(newReleases[i].genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text');
var p = document.createTextNode(newReleases[i].description);
cardDescr.appendChild(p);
}) //end of forEach
} // end of for-loop
Use either for or forEach(), not both.
for (var i = 0; i < newReleases.length; i++) {
var bookTitle = document.getElementsByClassName('card-header')[0]
var t = document.createTextNode(newReleases[i].title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')[0]
var a = document.createTextNode(newReleases[i].authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle")[0];
var genre = document.createTextNode(newReleases[i].genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text')[0];
var p = document.createTextNode(newReleases[i].description);
cardDescr.appendChild(p);
}
or
newReleases.forEach(function(release) {
var bookTitle = document.getElementsByClassName('card-header')[0]
var t = document.createTextNode(release.title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')[0]
var a = document.createTextNode(release.authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle")[0];
var genre = document.createTextNode(release.genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text')[0];
var p = document.createTextNode(release.description);
cardDescr.appendChild(p);
});
When you use forEach() you don't need to subscript the array variable, you just use the parameter to the callback function.

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 = []

Accessing Excel's Object Model from Javascript

I have excel as an activeX object in javascript. I seem to be missing something with reards to how to interact with the object model from there. My watch window shows the value of the "Value" property of the range I am trying to pull data from as "undefined" when I try to assign "range.Value" to an array.
Unfortunately I am unable to update the outdated browsers on my machine at work so I cannot upload pictures.
My script:
function open_files(A, B, C)
{
var excel = new ActiveXObject("Excel.Application");
excel.Visible=true;
excel.DisplayAlerts = false;
var wbA = excel.Workbooks.Open(document.getElementById(A).value);
var wbB = excel.Workbooks.Open(document.getElementById(B).value);
var wbC = excel.Workbooks.Open(document.getElementById(C).value);
excel.EnableEvents = false;
excel.ScreenUpdating = false;
excel.Calculation = -4135 //xlCalculationManual enumeration;
var wb_collection = [wbA, wbB, wbC];
excel.Application.Run("'" + wbA.name + "'" + '!update_links');
var CLIN_list = [wbA.Sheets("Control Form").Range("B62:B141").value(1)]
for (i = 0; i = CLIN_list.length; i++)
{
if (CLIN_list(i) > 0)
{
var CLIN_list_count = i
}
}
var decrement_range_start = wbA.Sheets("Fee & Decrement Table").Range("AJ14")
//for (i = 0; i < 80; i++){
//Sheets("Fee & Decrement Table").Cells(decrement_range_start.column+i
// Model Setup for VBA
wbA.Sheets("CONTROL FORM").Activate
wbA.Sheets("CONTROL FORM").OLEObjects("TextBox21").Object.Text = wbB.fullname
wbA.Sheets("CONTROL FORM").OLEObjects("TextBox22").Object.Text = wbC.fullname
excel.Application.Run("'" + wbA.name + "'" + '!Run_JPO');
I found an answer on another forum. A Range cannot be assigned directly to a js array, it has to be converted. The line below works to fill my CLIN_list variable.
var CLIN_list = new VBArray(wbA.Sheets("Control Form").Range("B62:B141").value).toArray();

Nested Loop Javascript

can someone please let me know, whats wrong with the format of my nested loop. i dont seem to be getting it to loop correctly. the values that are the same are not being generated together.
for (var field in Itemlist) {
for (var field in EstItems){
console.log(Itemlist[field].item_id, EstItems[field].zoho_id);
if (EstItems[field].zoho_id == Itemlist[field].item_id) {
console.log("We are In");
var id = EstItems[field].itemID;
var itemID = EstItems[field].zoho_id;
var barcode = EstItems[field].barcode;
//var EstBarcode = EstItems[field].itemID;
var description = EstItems[field].description;
var cost = EstItems[field].cost;
var shippingCost = "500";
var clearingCharges = "";
var quantityOrdered = 1;
//var quantityRecvd = EstItems[field].itemID;
//var quantityRTD = EstItems[field].itemID;
var selected = 0;
var totalcost = (cost*quantityOrdered)+parseFloat(shippingCost);
var categoryID = 0;
}
}
}
You have a scope problem introduced by overwriting a previous variable.
for (var field in Itemlist) {
// `field` here is a property from ItemList
for (var field in EstItems){
// `field` here is a property from EstItems
// Any attempt to access the `field` var from the outer loop will fail, as it has been overwritten.
}
}
Rename field for either loop.

Accessing Stored Object

I have an object "Driver" defined at the beginning of my script as such:
function Driver(draw, name) {
this.draw = draw;
this.name = name;
}
I'm using this bit of JQuery to create new drivers:
var main = function () {
// add driver to table
$('#button').click(function ( ) {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#"+draw;
var name2 = "driver"+draw
console.log(draw2);
console.log(name2);
if($(name2).text().length > 0){
alert("That number has already been selected");}
else{$(name2).text(name);
var name2 = new Driver(draw, name);}
});
That part is working great. However, when I try later on to access those drivers, the console returns that it is undefined:
$('.print').click(function ( ) {
for(var i=1; i<60; i++){
var driverList = "driver"+i;
if($(driverList.draw>0)){
console.log(driverList);
console.log(driverList.name);
}
If you're interested, I've uploaded the entire project I'm working on to this site:
http://precisioncomputerservices.com/slideways/index.html
Basically, the bottom bit of code is just to try to see if I'm accessing the drivers in the correct manner (which, I'm obviously not). Once I know how to access them, I'm going to save them to a file to be used on a different page.
Also a problem is the If Statement in the last bit of code. I'm trying to get it to print only drivers that have actually been inputed into the form. I have a space for 60 drivers, but not all of them will be used, and the ones that are used won't be consecutive.
Thanks for helping out the new guy.
You can't use a variable to refer to a variable as you have done.
In your case one option is to use an key/value based object like
var drivers = {};
var main = function () {
// add driver to table
$('#button').click(function () {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#" + draw;
var name2 = "driver" + draw
console.log(draw2);
console.log(name2);
if ($(name2).text().length > 0) {
alert("That number has already been selected");
} else {
$(name2).text(name);
drivers[name2] = new Driver(draw, name);
}
});
$('.print').click(function () {
for (var i = 1; i < 60; i++) {
var name2 = "driver" + i;
var driver = drivers[name2];
if (driver.draw > 0) {
console.log(driver);
console.log(driver.name);
}

Categories

Resources