jeudi 26 mars 2015

Transaction fail on Ajax success on Document Ready using Cordova SQLite plugin

I know this is about asynchornous function after reading this: indexedDB: issue calling transaction function


However, I still couldn't figure out how to improve my code after reading all the asynchornous stuffs, here is my code:


index.html



<script src="cordova.js"></script>
<script src="js/db.js"></script>

<script>
$( document ).ready(function() {
getLangText("zh");

var thisShopId;

$( "#list-view-section" ).hide();
$( "#toggle-chart-view" ).hide();

$.ajax(
{
type: "GET",
url: "http://mysite/myjson/",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function(data){

thisShopId = data[0].ShopId;

addParam("ShopId", thisShopId);

},
error: function (xhr) {
alert(xhr.responseText);
}
}
);
});
</script>


db.js



document.addEventListener("deviceready", init, false);
document.addEventListener("touchstart", function() {}, false);

var app = {};
app.db = null;

function init() {
app.openDb();
app.createTable();
}

app.openDb = function() {
app.db = window.sqlitePlugin.openDatabase("BasicInfo");
}

app.createTable = function() {
var db = app.db;
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS workingparameters(ID INTEGER PRIMARY KEY ASC, name TEXT, value TEXT, added_on DATETIME)", [], app.onSuccess, app.onError);
});
}

app.addParam = function(paramText, paramValue) {
var db = app.db;
db.transaction(function(tx) {
var addedOn = new Date();
tx.executeSql("INSERT INTO workingparameters(name, value, added_on) VALUES (?,?,?)",
[paramText, paramValue, addedOn],
app.onSuccess,
app.onError);
});
}


From time to time, the following problem occurs: "Uncaught TypeError: Cannot read property 'transaction' of null"


Please tell me how to improve my code, thanks.


Aucun commentaire:

Enregistrer un commentaire