Access Database Via Javascript - javascript

I am creating a HTA application since my environment has restrictions. In any case I am trying to connect to an Access Database through a prototype. This prototype is suppose to get the information from the database but it always returns as "undefined". I am unable to determine as to why this is occurring as i am using the ActiveX controls that open that provider.
The Calling function
Please note that the access drivers are installed, the location is correct and the table does exists with content.
function GetX()
{
var db = new AccessDatabase("I:\\Office\\Access\\Sample.accdb");
db.Connect();
if (db.Status != 0) { return; }
// Remove all
$("#x").empty();
// The Query
var results = db.Select("SELECT x FROM Tracker");
// Get the results length
var arrayLength = results.length;
// Iterate through the results
for (var row = 0; row < arrayLength; row++)
{
$("#x").append("<option id='" + results[row][0] + ">" + results[row][0] + "</option>");
}
db.Disconnect();
}
The prototype object:
function AccessDatabase(databaseSource)
{
try
{
this.Connection = new ActiveXObject("ADODB.Connection");
this.Source = databaseSource;
this.Status = 0;
}
catch (err)
{
createNotification("Danger", "Unable to create ActiveX Control For Microsoft ");
this.Status = err.Number;
}
}
AccessDatabase.prototype.Connect = function()
{
try
{
var provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + this.Source;
this.Connection.Open(provider);
}
catch (err)
{
createNotification("Danger", "Database Failed To Connect. Was the Source correct?<br>Details: " + err.message);
this.Status = err.Number;
}
}
AccessDatabase.prototype.Disconnect = function()
{
this.Connection.Close();
}
AccessDatabase.prototype.Select = function (selectQuery)
{
try
{
// Open the recordset
var recordSet = new ActiveXObject("ADODB.Recordset");
recordSet.Open(selectQuery, this.Connection);
// Check for null results
if (recordSet.RecordCount == null || recordSet.RecordCount == -1)
{
createNotification("Error", "No record was found for the query provided <br> Query: <small>"
+ selectQuery + "</small>");
recordSet.Close();
this.Status = -1;
return null;
}
alert("Record Count:" + recordSet.RecordCount);
// Convert To Array
var returnValue = recordSet.GetRows();
recordSet.Close();
// Return the array
return returnValue;
}
catch (err)
{
createNotification("Warning", "Query Could Not Execute Due to an error. <br>Details: " + err.message);
this.Status = err.Number;
}
}

Related

Request in NodeJS async waterfall return undefined

I'm pretty new to async on node js. I use the waterfall method while parsing a xml file like this:
$('situation').each( function(){
var situation = [];
$(this).find('situationRecord').each( function(i){
var record = this;
async.waterfall([
function (callback){
var filter = {
startLocationCode: $(record).find('alertCMethod2SecondaryPointLocation').find('specificLocation').text(),
endLocationCode: $(record).find('alertCMethod2PrimaryPointLocation').find('specificLocation').text(),
overallStartTime: $(record).find('overallStartTime').text(),
overallEndTime: $(record).find('overallEndTime').text()
}
callback(null, filter, record);
},
function (filter, record, callback){
var timestamp = new Date().toDateInputValue();
var startDbResponse = 0;
var endDbResponse = 0;
if((filter.startLocationCode != '') && new Date(timestamp) >= new Date(filter.overallStartTime) && new Date(timestamp) <= new Date(filter.overallEndTime) ){
startDbResponse = locationCodeToGeodataRequst.geodataByLocationcode(filter.startLocationCode);
endDbResponse = locationCodeToGeodataRequst.geodataByLocationcode(filter.endLocationCode);
}
console.log("startDbResponse: ", startDbResponse);
console.log("endDbResponse: ", endDbResponse);
callback(null, filter, record, startDbResponse, endDbResponse);
},
function (filter, record, startDbResponse, endDbResponse, callback){
console.log("startDbResponse: ", startDbResponse);
console.log("endDbResponse: ", endDbResponse);
var situationRecord = createSituationRecord($, record, filter.startLocationCode, filter.endLocationCode, startDbResponse, endDbResponse);
console.log(situationRecord);
},
function (situationRecord, callback){
situation[i] = { situationRecord };
}
],
function(err, results){
console.error("There was an error by filtering the xml file");
console.error(err);
});
})
if(situation.length > 0){ //if situation is not empty
locations.push(situation);
}
})
console.log(locations);
}
In this part of the waterfall I make a request to my database with locationCodeToGeodataRequst.geodataByLocationcode(filter.startLocationCode); but startDbResponse and endDbResponse is undefined :
....
function (filter, record, callback){
var timestamp = new Date().toDateInputValue();
var startDbResponse = 0;
var endDbResponse = 0;
if((filter.startLocationCode != '') && new Date(timestamp) >= new Date(filter.overallStartTime) && new Date(timestamp) <= new Date(filter.overallEndTime) ){
startDbResponse = locationCodeToGeodataRequst.geodataByLocationcode(filter.startLocationCode);
endDbResponse = locationCodeToGeodataRequst.geodataByLocationcode(filter.endLocationCode);
}
console.log("startDbResponse: ", startDbResponse);
console.log("endDbResponse: ", endDbResponse);
callback(null, filter, record, startDbResponse, endDbResponse);
},
....
The request by it self works because a console.log in the request module show the correct data. So I don't understand why its undefined.
This is the request module:
exports.geodataByLocationcode = function geodataByLocationcode(locationcode){
let sql = "SELECT * FROM tmc WHERE LOCATION_CODE = " + locationcode;
let query = db.query(sql, (err, result) =>{
if(err == null){
//console.log(result);
return result;
}else{
console.log("Error by getting item from db: " + err);
throw err;
}
});
}
This is a snipped of the console.log:
....
startDbResponse: undefined
endDbResponse: undefined
startDbResponse: undefined
endDbResponse: undefined
startDbResponse: 0
endDbResponse: 0
startDbResponse: 0
endDbResponse: 0
[]
//here comes the output of the requests as json objects
....
move the console log to the last function of async. As Manjeet pointed out async takes time and console prints early.
function (situationRecord, callback){
situation[i] = { situationRecord };
if(situation.length > 0){ //if situation is not empty
locations.push(situation);
}
})
console.log(locations);
}
}

Javascript global variables and references to them and their parts

I'm writing little snippets to learn more about using Javascript with API's, and have stumbled onto another problem I can't figure out on my own. I have a global variable (object?) "coins", read in from the API, and its' data field "symbol". I can use "symbol" to reference the data held there, in part of my code, without any errors. Later in the code, I use it again, and I get an error about it being undefined, despite the fact that the values returned from using it, are both defined, and, what I expected. While we are at it, maybe someone can tell me why I assign values to global variables (declared outside of all of the functions), but the variables when called, are "undefined". To see it in action, visit www.mattox.space/XCR and open up dev tools.
/*
FLOW:
get ALL coins, store NAME and SYMBOL into an object.
loop over the names object comparing to $SYMBOL text from form, return the NAME when found.
hit the API again, with the $NAME added to the URL.
create a table row.
insert data from second API hit, into table row
SOMEWHERE in there, do the USD conversion from BTC.
*/
//var name = getName();
var bitcoinValue = 0;
var coins = new Array;
var form = ""; // Value pulled from the form
var symbol = ""; // "id" on the table
var id = ""; // value pulled from the table at coins[i].id matched to coins[i].symbol
var formSym = "";
var formUSD = 0;
var formBTC = 0;
var form24h = 0;
function run() {
getFormData();
allTheCoins("https://api.coinmarketcap.com/v1/ticker/");
testGlobal();
}
function testGlobal() {
console.log("These are hopefully the values of the global variables");
console.log(formSym + " testGlobal");
console.log(formUSD + " testGlobal");
console.log(formBTC + " testGlobal");
console.log(form24h + " testGlobal");
}
function getFormData(){ //This function works GREAT!
form = document.getElementById("symbol").value //THIS WORKS
form = form.toUpperCase(); //THIS WORKS
}
function allTheCoins(URL) {
var tickerRequest = new XMLHttpRequest();
tickerRequest.open('GET', URL);
tickerRequest.send();
tickerRequest.onload = function() {
if (tickerRequest.status >= 200 && tickerRequest.status < 400) {
var input = JSON.parse(tickerRequest.responseText);
for(var i in input)
coins.push(input[i]);
testFunction(coins);
}
else {
console.log("We connected to the server, but it returned an error.");
}
console.log(formSym + " allTheCoins!"); // NOPE NOPE NOPE
console.log(formUSD) + " allTheCoins!"; // NOPE NOPE NOPE
console.log(formBTC + " allTheCoins!"); // NOPE NOPE NOPE
console.log(form24h + " allTheCoins!"); // NOPE NOPE NOPE
}
}
function testFunction(coins) {
for (var i = 0; i < coins.length; i++) {
if (coins[i].symbol == form) { // But right here, I get an error.
formSym = coins[i].name;
formUSD = coins[i].price_usd;
formBTC = coins[i].price_btc;
form24h = coins[i].percent_change_24h;
console.log(formSym + " testFunction");
console.log(formUSD + " testFunction");
console.log(formBTC + " testFunction");
console.log(form24h + " testFunction");
//DO EVERYTHING RIGHT HERE! On second thought, no, this needs fixed.
}
else if (i > coins.length) {
formSym = "Error";
formUSD = 0;
formBTC = 0;
form24h = 0;
}
}
}
/*
if (24h >= 0) {
colorRED
}
else {
colorGreen
}
*/
here is a possible way of doing it that you can get inspired by. its based on a httpRequest promise that set the headers and method.
let allTheCoins = obj => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(obj.method || obj.method, obj.url);
if (obj.headers) {
Object.keys(obj.headers).forEach(key => {
xhr.setRequestHeader(key, obj.headers[key]);
});
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => reject(xhr.statusText);
xhr.send(obj.body);
});
};
allTheCoins({
url: "https://api.coinmarketcap.com/v1/ticker/",
method: "GET",
headers: {"Accept-Encoding": "gzip"}
})
.then(data => {
ParseCoins(data);
})
.catch(error => {
console.log("We connected to the server, but it returned an error.");
});
function ParseCoins(data) {
const coins = JSON.parse(data);
const form = getFormVal();/*retrieve form val*/
const id = getTableId(); /*retrieve table id*/
const bitcoinValue = getBitcoinVal();/*retrieve bitcoin Value*/
const final_result = [];
for (let i = 0, len = coins[0].length; i < len; i++) {
const coin = coins[0][i];
for (let ii in coin) {
if (coin.hasOwnProperty(ii)) {
if (coin[ii].symbol == form) {
let element = {
formSym: coin[ii].name,
formUSD: coin[ii].price_usd,
formBTC: coin[ii].price_btc,
form24h: coin[ii].percent_change_24h
};
final_result.push(element);
}
}
}
}
coontinueElseWhere(final_result);
}

XMLHttpRequest.responseXML is NULL even when .readystate == 4

I am using javascript to load in data from a XML file. The file is not being loaded in after an if statement that checks the ready state and the status. The ready state brings back 4 and the status brings back 200, so the last condition (the responseXML) should not be null, but for some reason, it remains null and the XML file is not loaded.
function load() {
try {
console.log("in load");
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", function() {
processResponse();
}, false);
asyncRequest.open('GET', 'Catalog.xml', true);
asyncRequest.send(null);
} catch (exception) {
alert("Request Failed");
console.log("failed");
}
}
function processResponse() {
console.log(asyncRequest.readyState + " response" + asyncRequest.status + asyncRequest.responseXML);
if (asyncRequest.readyState == 4 && asyncRequest.status == 200 && asyncRequest.responseXML) {
console.log("found");
var planets = asyncRequest.responseXML.getElementsByTagName("planet");
var name = document.getElementById("planetinfo").value;
console.log(name);
for (var i = 0; i < planets.length; ++i) {
var planet = planets.item(i);
var planetName = planet.getElementsByTagName("name").item(0).firstChild.nodeValue;
if (name == planetName) {
document.getElementById("name").innerHTML = planet.getElementsByTagName("name").item(0).firstChild.nodeValue;
document.getElementById("discovered").innerHTML = planet.getElementsByTagName("discovered").item(0).firstChild.nodeValue;
document.getElementById("distance").innerHTML = planet.getElementsByTagName("distance").item(0).firstChild.nodeValue;
document.getElementById("contact").innerHTML = planet.getElementsByTagName("contact").item(0).firstChild.nodeValue;
document.getElementById("image").innerHTML = "<img src='../images/" + planet.getElementsByTagName("image").item(0).firstChild.nodeValue + "' + '/ width = '250' height = '250'>";
}
}
}
}
This is the code from the javascript file that pertains to the loading of the XML. Opening up the console shows logs that tells me the code does not get past the if statement checking the asyncRequest.

Java Script array get undefined

when I print the whole array it's print.but if I try to print element by element it's print as undefined.this is my function. I print the arrays at end of the function.client functions are used to connect ajax API.i tried to get integer id that matching to a specific string from database via ajax functions and push them into the two arrays.
function fetch() {
var arrayForClass = [];//this is a array get undefined at the end
var arrayForMessage = [];//this is a array get undefined at the end
exceptionPattern ="";
receivedData.length = 0;
var queryInfo;
var queryForSearchCount = {
tableName: "LOGANALYZER",
searchParams: {
query: "_eventTimeStamp: [" + from + " TO " + to + "]",
}
};
client.searchCount(queryForSearchCount, function (d) {
if (d["status"] === "success" && d["message"] > 0) {
var totalRecordCount = d["message"];
queryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query: "_eventTimeStamp: [" + from + " TO " + to + "]",
start: 0, //starting index of the matching record set
count: totalRecordCount //page size for pagination
}
};
client.search(queryInfo, function (d) {
var obj = JSON.parse(d["message"]);
if (d["status"] === "success") {
for (var i = 0; i < obj.length; i++) {
if(obj[i].values._level === "ERROR" || obj[i].values._level === "WARN"){
receivedData.push([{
date: new Date(parseInt(obj[i].values._eventTimeStamp)).toUTCString(),
level: obj[i].values._level,
class: obj[i].values._class,
content: obj[i].values._content,
trace: (obj[i].values._trace ? obj[i].values._trace : ""),
timestamp: parseInt(obj[i].values._eventTimeStamp)
}]);
}else{
continue;
}
}
console.log(receivedData);
for (forLoopI = 0; forLoopI < receivedData.length; forLoopI++){
var className = receivedData[forLoopI][0].class;
var strclassname = className.toString();
var messageContent = receivedData[forLoopI][0].content;
queryInfo = {
tableName: "EXCEPTION_CLASS_FOR_ERROR_PATTERNS",
searchParams: {
query: "class_name: "+ strclassname + "",
start: 0, //starting index of the matching record set
count: 1 //page size for pagination
}
};
client.search(queryInfo,function(d){
var obj = JSON.parse(d["message"]);
if (d["status"] === "success") {
var num = obj[0].values.id;
var strnum = num.toString();
arrayForClass.push(strnum);
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","error while creating the error pattern" +
" please try again"));
}
},function(error){
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
queryInfo = {
tableName: "ERROR_MESSAGE_CONTENTS",
searchParams: {
query: "message: \""+ messageContent + "\"",
start: 0, //starting index of the matching record set
count: 1 //page size for pagination
}
};
client.search(queryInfo,function(d){
var obj = JSON.parse(d["message"]);
console.log(obj);
if (d["status"] === "success") {
var num2 = obj[0].values.id;
var strnum2 = num2.toString();
arrayForMessage.push(strnum2);
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","error while creating the error pattern" +
" please try again"));
}
},function(error){
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
}
}
}, function (error) {
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","there are no error patterns which include this error" +
" please try another one"));
}
}, function (error) {
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
console.log("------------------");
for (var j = 0; j < 8; j++) {
console.log(arrayForClass[j]);//prints undefine
}
console.log("------------------");
console.log(arrayForClass[0]); //prints undefine
console.log(arrayForClass);//prints corectly
console.log(arrayForMessage);//printd corectly
}
Your API call is asynchronous, which mean it's continue working to the next line even your call is not finished.
You get undefined because your console.log reference to the not exists yet variable. arrayForClass is empty at that moment, so arrayForClass[0] is not exists.
Next line you get correct result because you console.log to an existing variable, even it's empty at the moment, but your debugger tool is trying to be smart by update it for you in the console when your data came in.
if you really want to see the actual value at that point, you need to somehow make it immutable, for example :
console.log(JSON.parse(JSON.stringify(arrayForClass)));
This is only explain why you get data in the console like that.If you need to use those variable, It's has to be done inside those callback function regarding each calls.

Javascript call by reference not working

I read this and tried implementing my function so that data doesn't change back, but it isn't working with me.
I have an array of objects, where I send them one by one to another function, to add data.
queries.first(finalObject.sectionProjects[i]);
for each one of the sectionProjects, there is a variable achievements, with an empty array.
Upon sending each sectionProject to the queries.first function, I reassign achievements,
finalObject.sectionProjects[i].achievements = something else
When I return from the queries.first function, I lose the data I added.
Am I doing something wrong?
Here's the function:
module.exports = {
first:function(aProject) {
// Latest achievements
var query =
" SELECT ta.description, ta.remarks, ta.expectedECD " +
" FROM project pr, task ta, milestone mi " +
" WHERE pr.ID = mi.project_ID AND mi.ID = ta.milestone_ID " +
" AND ta.achived = ta.percent AND pr.ID = " + aProject.project_id +
" ORDER BY pr.expectedECD " +
" LIMIT 5;"
;
var stringified = null;
pmdb.getConnection(function(err, connection){
connection.query(query, function(err, rows){
if(err) {
throw err;
}else{
var jsonRows = [];
for( var i in rows) {
stringified = JSON.stringify(rows[i]);
jsonRows.push(JSON.parse(stringified));
}
connection.release();
aProject.achievements = jsonRows;
upcomingTasks(aProject);
}
});
});
}
}
This is pmdb.js:
var mysql = require("mysql");
var con = mysql.createPool({
host: "localhost",
user: "user",
password: "password",
database: "database"
});
module.exports = con;
This is the main function that calls queries.first:
// ...Code...
//Number of section projects
var len = jsonRows.length;
console.log("Number of section projects: " + len);
var internal_counter = 0;
function callbackFun(i){
(finalObject.sectionProjects[i]).achievements = [];
queries.first(finalObject.sectionProjects[i]);
if(++internal_counter === len) {
response.json(finalObject);
}
}
var funcs = [];
for (var i = 0; i < len; i++) {
funcs[i] = callbackFun.bind(this, i);
}
for (var j = 0; j < len; j++) {
funcs[j]();
}
Read That Answer twice. Objects acts as a wrapper for the scalar primitive property. You are passing the Objects in to the "queries.first" function.
See this Object reference issue
Edited for the sample code
pmdb.getConnection(function(err, connection){
connection.query(query, function(err, rows){
if(err) {
throw err;
}else{
var jsonRows = [];
for( var i in rows) {
stringified = JSON.stringify(rows[i]);
jsonRows.push(JSON.parse(stringified));
}
connection.release();
aProject.achievements = jsonRows;
upcomingTasks(aProject)
}
});
});
that is not a problem. change it like this. "upcomingTasks" is not a callback function. it is execute after assign the achievements in aProject

Categories

Resources