Web SQL Delete Query not Working - javascript

i am writing a code for cordova app to delete all data from Web SQL DB table on function call.
Here is the code
function removeitem(){
db.transaction(function (tx) {
tx.executeSql("DELETE FROM hist", [], function (tx, result) {
toast('Deleted');
}, function (error) {
alert(error.code);
});
}, function (error) {
alert(error);
});
}
But the code doesn't work and always give alert
[Object SQLError]
Other functions for creating table, updating records are working fine but delete query is creating problem. Please help guys to identify the problem.
THANKS

As long as you want to delete all data from table, try below statement:
TRUNCATE TABLE hist;
tx.executeSql("TRUNCATE TABLE hist",[],
function(tx,results){console.log("Successfully Emptied")},
function(tx,error){console.log("Could not Empty")}
);
or
tx.executeSql("DELETE FROM hist",[],
function(tx,results){console.log("Successfully Emptied");},
function(tx,error){console.log("Could not Empty");}
);
One of them must work.
Full code:
var db.transaction(function (tx) {
tx.executeSql("DELETE FROM hist",[],
function(tx,results){
console.error("Successfully Emptied");
},
function(tx,error){
console.error("Error: " + error.message);
}
)
});

I just noticed, it was a silly mistake. I was calling
toast('Deleted');
function which was not yet defined therefore the statement was failing.
Sorry for my bad and thanks for helping.

Related

How get info from WebSocket using php?

I want get last transaction from blockchain.info On this site has API Websocket. But i can use API Websocket only for JavaScript. I can get last transaction using this code
<script type="text/javascript">
var conn = new WebSocket('ws://ws.blockchain.info/inv');
conn.onopen = function () {
console.log('open');
conn.send('{"op":"unconfirmed_sub"}');
}
conn.onclose = function () {
console.log('close');
}
conn.onerror = function (error) {
console.log('websocket error: ' + error);
}
conn.onmessage = function (e) {
console.log(e);
}
</script>
But i need get info above using php and after save in mysql. How can I get it through php?
Thank you in advance!
I found a library that solves the problem it phpws
Thanks to all.

Phonegap: insert query sqlite when login success

I build an mobile app hibrid base with phonegap and jquery mobile. My app has a login system, retrieve data from database in server and insert it to sqlite when login succes, so the app can access to the data even it's offline.
i use plugin from litehelpers. And this my sql connect script in database.js:
document.addEventListener("deviceready", connectDB, false);
var kode = JSON.parse(window.localStorage['konfirmasi']);
//create or open Database
function connectDB(){
db = window.sqlitePlugin.openDatabase("konfirmasi", "1.0", "Data Konfirmasi Pengiriman", "1000");
db.transaction(populateDB,successCB,errorCB);
}
//create table and insert some record
function populateDB(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS data_konfirmasi (kode_transaksi text, status text) UNIQUE(kode_transaksi)");
}
//function will be called when an error occurred
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
console.log("Connected to database!");
//db.transaction(queryDB,errorCB);
}
function insertDB(tx){
for (var i = kode.length - 1; i >= 0; i--) {
tx.executeSql("INSERT INTO data_konfirmasi VALUES ("+kode[i]+", 'Belum Terkirim');");
};
}
function queryDB(){
db.transaction(insertDB,errorCB,querySuccess);
}
function querySuccess(){
console.log('Insert query success!');
}
function dropDB(){
db.transaction(dropQuery,errorDrop,successDrop);
}
function dropQuery(tx){
tx.executeSql("DROP TABLE IF EXIST data_konfirmasi");
}
function successDrop(){
console.log('Drop table successful');
}
function errorDrop(err){
console.log('Drop table unsuccessful, Error code: '+err.code);
}
function selectData(err){
db.transaction(selectQuery, errorCB, successQuery)
}
function selectQuery(tx){
tx.executeSql('SELECT * FROM data_konfirmasi',[], querySuccess, errorCB);
}
function querySuccess(tx, results) {
console.log("Returned rows = " + results.rows.length);
// this will be true since it was a select statement and so rowsAffected was 0
if (!results.rowsAffected) {
console.log('No rows affected!');
return false;
}
// for an insert statement, this property will return the ID of the last inserted row
console.log("Last inserted row ID = " + results.insertId);
}
Then, when user login for the first time and success it will retrieve data from server with json, and i want my app to insert retrieved data to sqlite. So, how to put the query for login success only? After that i want to make it DROP table and clear localStorage when it's logout.
This is my login and logout script (main.js):
$(document).on('pageinit','#login',function(){
$(document).on('click','#submit',function(){
if($('#username').val().length>0&&$('#password').val().length>0){
var un = $('#username').val();
var pw = $('#password').val();
$.ajax({
url:'http://qrkonfirmasi.16mb.com/delivery/login.php',
data:{ username : un,
password : pw
},
type:'post',
async:'false',
dataType: 'json',
beforeSend:function(){
$.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
},
complete:function(){
$.mobile.loading('hide');
},
success:function(result){
console.log(result);
if(result.status==true){
user.name=result.message;
window.localStorage.setItem('konfirmasi', JSON.stringify(result.data));
console.log('Kode: ', JSON.parse(window.localStorage['konfirmasi']));
var kode = JSON.parse(window.localStorage['konfirmasi']);
console.log('Array length: '+kode.length);
queryDB();
console.log('Login berhasil');
$.mobile.changePage("#konfirmasi");
window.localStorage.setItem('uname', un);
window.localStorage.setItem('passwd', pw);
console.log(window.localStorage['uname']);
}else{
alert('Login gagal. Username atau password tidak sesuai');
}
},
error:function(request,error){
alert('Koneksi error. Silahkan coba beberapa saat lagi!');
}
});
}else{
alert('Masukkan username dan password!');
}
return false;
});
});
$(document).on('pagebeforeshow','#konfirmasi',function(){
$.mobile.activePage.find('.welcome').html('<h3>Selamat Datang '+user.name+'</h3>' );
});
$(document).off('click').on('click','#logout',function(){
window.localStorage.clear();
dropDB();
$.mobile.changePage("#home");
});
function exitFromApp(){
navigator.app.exitApp();
}
So, am i at the right way for logout script? I didn't know it works or not because i still cannot try it because the login script still error when i try it with insert query.
Can someone help me make it done, please?
Where are u calling this piece of code from?
function insertDB(tx,val){
for (var i = kode.length - 1; i >= 0; i--) {
tx.executeSql('INSERT INTO konfirmasi VALUES ('+a[i]+');',querySuccess,errorCB);
};
}
If you are calling it from a transaction, then the "val" parameter will not be passed to the insertDB function directly. You might try the following thing:
val = [];
db.transaction(function(tx){
insertDB(tx, val);
}, errorCB);
Moreover, make sure that the stements always run within a db.transaction context
Have fun!

WebSQL update isn't working

today i was helping a friend with a solution and in the runtime the UPDATE in my PC works and in his pc doesn't . we've checked the databases and they are all Okay, i tried to upload the code to my raspberry pi and it doesn't work. we've tried to debug the code, and it went straight to the callBack function (it didn't gave error).
The databese is based in WebSQL and the code is this one:
$('#save').click(function(){
var db=openDatabase('ATS_db2', '1.0', 'base de dados ATS', 2*2048*2048);
db.transaction(function (tx){
var nome =$('#alteranome').val();
var bi =$('#alterabi').val();
var nif =$('#alteranif').val();
var morada=$('#alteramorada').val();
var contatos = $('#alteracontatos').val();
var id = $('#Id_cliente').val();
tx.executeSql('UPDATE Cliente Set Nome=? ,Bi=? ,Nif=? ,Morada=? ,Contatos=? where Id_cliente = ?;',[nome,bi,nif,morada,contatos,id],function(tx,results){
alert("Cliente alterado com sucesso");
//location.reload();
},errorHandler);
});
});
errorHandler = function (transaction, error) {
// returns true to rollback the transaction
debugger;
alert("Error processing SQL: "+ error);
return true;
}
Can someone know what is happening?
Ty ;)

Inserting json data into <p> tags with deployd (nobackend)

I am using a javascript Get call to grab the json data for a collection I created in deployd. I got this code directly from the deployd backend. It gives me a json array that is put into the console, but I am far from figuring out how to parse the json not sure if thats the right term, and output it into seperate p tags for each item within in the collection.
I also have included jQuery and I am assuming based on what I have looked into online that it makes it much easier to do so. Also if there is a better library than jQuery to learn to do this with, or something that makes more sense for deployd lets say Angular, I would love to be steered in the right direction.
Here is the javascript get request provided.
dpd.things.get(function (result, err) {
if(err) return console.log(err);
console.log(result);
});
I have tried looking at a example app off the deployd site to see how they did it but havent quite figured it out here is my failed attempt below
<body>
<h1>Welcome to Deployd!</h1>
<p>You've just created a Deployd app. You can add front-end files in the <code>public</code> folder.</p>
<p>If you're new to Deployd, have a look at the Getting Started Guide or <a href="http://docs.deployd.com/docs/getting-started/your-first-api.md">Hello World Tutorial<a>.</p>
<p class="hide" id="empty">You don't have any todos! Add one now:</p>
<ul id="todos" class="unstyled"></ul>
</body>
<script>
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
// $label = $('<label class="checkbox">')});
$el.appendTo('#todos');
$('#empty').hide();
}
</script>
NEW RECCOMENDED CODE NOT WORKING
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
$el.text(thingy);
$el.appendTo('#todos');
$('#empty').hide();
}
Here is the site running on localtunnel so you can see the console. https://twig.localtunnel.me
Try adding 'thingy' in the code so it will display the items returned from the collection; Just make sure a collection is being returned.
If thingy is plain text:
var $el = $('<li>')
$el.text(thingy);
If thingy includes html with text:
var $el = $('<li>')
$el.html(thingy);
I ended up doing this in the end based off of this stack overflow answer
dpd.things.get(function(result, error) {
console.log(result);
$.each(result, function(i,result){
content = '<p id=" ' + result.name + ' ">'
+ result.name + '</p>' + '<p>' + result.about +
'</p>' + '<p>' + result.id + '</p>'
$(content).appendTo("#test");
});
});

Phonegap-Android-sqlite using Javascript. How to connect?

I am new to Android-Phonegap dev. I am creating a project using Eclipse in Windows XP.
I am using sqlite database. I saw the sample code in the docs. But I'm not able to execute this example. I am not getting the required results.
Suppose I want to get all the entries in the table demo in tabular format, HTML. What will the code be in index.html? For that, what is the procedure and what is the step by step procedure for doing this? Or else any better tutorials which help me to do this?
Thanks in Advance
Dnyan.
in main.js you add this
rowsDataHandler = function(transaction, results) {
// Handle the results
var html = "<ul>";
for (var i=0; i<results.rows.length; i++) {
var row = results.rows.item(i);
html += '<li>'+row['data']+'</li>\n';
}
html +='</ul>';
document.getElementById("mydata").innerHTML = html;
}
// load the currently selected icons
loadRows = function(db) {
try {
db.executeSql('SELECT * FROM DEMO',[], rowsDataHandler, errorCB);
} catch(e) {alert(e.message);}
}
in index.html you add this row inside body
<div id="mydata"></div>
One thing to bear in mind is that if you aren't testing the application on a device or in an emulator, but rather in a browser like Chrome or Safari,
document.addEventListener("deviceready", onDeviceReady, false);
won't work. What I've done is to comment out this line and just to put in a call to
onDeviceReady();
When I then test in the emulator I uncomment the "document…" line and comment out
onDeviceReady();
**html**
<input id="show" type="button" value="Show">
**js**
function globalError(tx, error)
{
alert("Error: " + error.message);
}
var db = window.openDatabase('TabOrder', '', 'Bar Tab Orders', 2500000);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS SubmiteData;', null, null, globalError);
tx.executeSql('CREATE TABLE IF NOT EXISTS SubmiteData (SubmiteDataId integer
primary key, UserId text, AuthNo number, LocId number,ProdId number,
CardId number, OrgLat text, OrgLng text, OrgTime text)',
null,
function()
{
SubmiteData("USER1",12345678,23434, 21212, 220232,
"9", "45", "23/06/2014");
},
globalError);
});
function SubmiteData(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx){
tx.executeSql('INSERT INTO SubmiteData(UserId, AuthNo, LocId, ProdId, CardId,
OrgLat, OrgLng, OrgTime) VALUES (?,?,?,?,?,?,?,?)', [UserId, AuthNo, LocId,
ProdId, CardId, OrgLat, OrgLng, OrgTime],
null,
globalError
);
});
}
function read(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM SubmiteData',
[],
function(tx, results)
{
for (var i=0; i<results.rows.length; i++)
{
var row=results.rows.item(i);
// alert("Id: " + row['UserId']);
var stringout = "LocId: " + row['LocId'] + "\n";
alert(stringout);
}
},
globalError
);
});
};
$(function()
{
$('#show').click(read);
});
this is the method to connect to a db using javascript
db = openDatabase("bprueba","1.0","Prueba_db",5*1023*1024);
SQL Statement Error Callback Reference

Categories

Resources