2

I have a first.js which I open the database:

$(function(){ 
    initDatabase();
});

function initDatabase() {

    try {
        if (!window.openDatabase) {
            alert('Local Databases are not supported by your browser. Please use a Webkit browser for this demo');
        } else {
            var shortName = 'MyDB';
            var version = '1.0';
            var displayName = 'First DB';
            var maxSize = 100000; // in bytes
            DB = openDatabase(shortName, version, displayName, maxSize);
            //dropTables();
            createTables();

        }
    } catch(e) {
        if (e == 2) {
            // Version mismatch.
            console.log("Invalid database version.");
        } else {
            console.log("Unknown error "+ e +".");
        }
        return;
    } 
}

Then, I want to execute sql statements from another file: second.js

function prueba_funcion () {
    DB.transaction(
        function (transaction) {
            transaction.executeSql("SELECT * FROM categorias;", [], nullDataHandler, errorHandler);
        }
    );
}

I receive this error: DB is not defined

In my HTML code I include first.js before second.js:

<script type="text/javascript" src="js/first.js"></script>
<script type="text/javascript" src="js/second.js"></script>

But I cant get it.

1 Answer 1

1

Your issue is caused by variable scope. If you want the variable DB to be global in scope, you have to instantize it outside of a function. Simply adding var DB = null; to first.js at the very top will probably solve your issue.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply. I receive this error now: Cannot call method 'transaction' of null
Then it sounds like you have other issues with whatever the function openDatabase returns. Looks like you're using Firebug... after you call openDatabase, console.log(DB) and go from there. This must be part of some framework or library? It is not part of vanilla javascript.
@Mateo, that is is because you are calling database before initializing it. $(function(){ initDatabase(); }); will wait for page to load. You don't need to wait. Just put initDatabase() at the very end of the first.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.