I've been trying to create a connection to an sqlite3 database with a script (main idea came from a stackoverflow answer) which is as follows. In the file "checkbook.js" I have the connection function and below the fuction that is supposed to use the connection, read the database and fill in some fields in a form:
function connect_db(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'checks.db', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
db = new SQL.Database(uInt8Array);
};
xhr.send();
}
function fill_status(){
var contents = window.db.exec("SELECT rowid,name FROM aux_status");
values = contents[0].values;
for (j=0;j<values.length;j++){
var select = document.getElementById('status')
var option = document.createElement('option');
select.appendChild(option);
option.value = values[0];
option.innerHTML=values[1];
}
}
The "checkbook.js" file is invoked in the "checks.html" file which is:
<!DOCTYPE html>
<html>
<head>
<title>Checkbook v0.0.1</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<link rel='icon' type='image/png' href='images/logo_ioniatex_bbg.png'>
<link rel='stylesheet' type='text/css' href='css/general.css'>
<script type='text/javascript' src='jscripts/general.js'></script>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' href='bootstrap-3.3.5-dist/css/bootstrap.min.css'>
<script src='bootstrap-3.3.5-dist/jquery-1.12.0.min.js'></script>
<script src='bootstrap-3.3.5-dist/js/bootstrap.min.js'></script>
<script src="sql.js"></script>
<script src="checkbook.js"></script>
</head>
<body>
...
<script>var db;connect_db();fill_status();</script>
</div>
</body>
</html>
But when I open the file (in Firefox) I get the message from firebug
TypeError: window.db is undefined
var contents = window.db.exec("SELECT rowid,name FROM aux_status");
What do I miss? I tried to declare the db variable with or without var
, even calling the function "fill_status" with window.db
but still I get the same answer. I would like to run the connect_db
function at the begining of the html file and after some code to run another which uses the global db
variable so as not to call an new connection to database for every data extraction I need.