0

I tried to JSON data insert into SqLit database in PhoneGap. I created a table with two columns, like this:

function setup(tx) {

    tx.executeSql('DROP TABLE IF EXISTS HEADER_DATA');
    tx.executeSql("create table if not exists bookinformation(inserkey TEXT, key TEXT)");
}

This code runs successfully and the table is created. Then, I insert JSON data into the bookinformation table, like this:

function dbReady() {
db.transaction(function(tx) {
        alert("5");
        $.getJSON('http://echo.jsontest.com/key/value/one/two',function(data){
         $.each(data, function(i, dat){
         tx.executeSql('INSERT OR REPLACE INTO bookinformation (inserkey, key) VALUES("'+data.one+'", "'+data.key+'")');    
        alert("completed");
    });
});     
    }, errorHandler, function() { alert('added row'); });
}

However, the insert statement fails. I get this error:

Uncaught InvalidStateError:Failed to execute 'executeSql' on 'SQLTransaction':SQL execution is disallowed

What is causing this error?

1 Answer 1

1

Old question but this might help others.

That error is usually caused by the transaction tx being stale.

This is because of the ajax call and by the time your ajax callback gets hit that tx object is no longer valid. The same happens if you use setTimeout or any time consuming non-Websql operation aswell.

To avoid that simply, create the transaction inside in the callback.

E.g

function dbReady() {
    $.getJSON('http://echo.jsontest.com/key/value/one/two',function(data) {
        db.transaction(function(tx) {
            alert("5");
            $.each(data, function(i, dat) {
                tx.executeSql('INSERT OR REPLACE INTO bookinformation (inserkey, key) VALUES("'+data.one+'", "'+data.key+'")');
            });
            alert("completed");
        }, errorHandler, function() { alert('added row'); });
    });
}
Sign up to request clarification or add additional context in comments.

Comments

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.