In the following function, how can I tell JS to wait for the return of my ajax call before proceeding with sql transaction.
The following sample code currently get the data properly, but the sql transaction is executed before the AJAX call populate my employees []
I try to place sql operation after succes but I got the following error
Uncaught DOMException: Failed to execute 'executeSql' on 'SQLTransaction': SQL execution is disallowed.
Here is part of the code
var addSampleData = function (tx, employees) {
var employees = [];
$.ajax({
url: 'my-path-to-my-json-answer',
success: function (value, status) {
employees.push(value);
},
error: function (XMLHttpRequest, textStatus, exception) {
console.log("Connection with the server fail.\n" + textStatus + 'status is: ' + exception);
}
});
var l = employees.length;
var sql = "INSERT OR REPLACE INTO leaderboard " +
"(id, uFname, uLname, uRegion, uCountry, uScore) " +
"VALUES (?,?,?,?,?,?)";
var e;
for (var i = 0; i < l; i = i + 1) {
e = employees[i];
tx.executeSql(sql, [e.id, e.uFname, e.uLname, e.uRegion, e.uCountry, e.uScore],
function () {
console.log('INSERT success');
},
function (tx, error) {
console.log('INSERT error: ' + error.message);
});
}
}
Any suggestion to improve that code are welcome.
.donesearch jquery for promise syntax