anyone know how to store the jsonp data from server in phonegap local database?
the code below can help to connect the phonegap android app to the server, but how to store the data in the phonegap local database?
$.ajax({
url: 'http://172.18.75.156/deals.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
output.text('successful');
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
db = window.openDatabase("SQL", 3, "PhoneGap Demo", 200000);
db.transaction(ajex_call, errorCB);
function ajex_call(tx) {
$.ajax({
url: 'http://172.18.75.156/deals.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
//item.obj
tx.executeSql("INSERT OR REPLACE INTO table-name(table-fields) values(?,?,..)", [array-data])
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
More information for local database http://docs.phonegap.com/en/2.2.0/cordova_storage_storage.md.html
Try like this hope this will work:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
db = window.openDatabase("SQL", 3, "PhoneGap Demo", 200000);
db.transaction(ajex_call, success, errorCB);
}
function ajex_call(tx) {
tx.executeSql('DROP TABLE IF EXISTS table_name');
tx.executeSql('CREATE TABLE IF NOT EXISTS table_name (fields_required_for_table)');
$.ajax({ url: 'http://172.18.75.156/deals.php', dataType: 'jsonp', jsonp: 'jsoncallback', timeout: 5000, success: function(data, status){
$.each(data, function(i,item){
tx.executeSql("INSERT OR REPLACE INTO table-name(table-fields) values(?,?,..)")
});
}, error: function(){
output.text('There was an error loading the data.');
}
});
}
function success(){
console.log('Success');
}
function error(){
console.log('error');
}
Check out HTML5's local storage.
PhoneGap's docs for it here:
I made a basic database controller class for this kind of thing a long time ago, managed to find it, hopefully it'll give you an idea.
Once you place the DataBaseCtrl code somewhere you'll be able to use it like this:
var myDatabase = DataBaseCtrl();
myDatabase.initWithConfig("DBShortName", "1.0", "MyDbName", 10000);
myDataBase.executeSql("SQL commands here...");
In your case, depending on how your data looks like you would set up your tables
myDataBase.executeSql("CREATE TABLE IF NOT EXISTS LOGS (id unique, log)");
myDataBase.executeSql("INSERT INTO LOGS (id, log) VALUES (1, 'foobar')");
myDataBase.executeSql("INSERT INTO LOGS (id, log) VALUES (2, 'logmsg')");
And maybe then use a loop to get all your data in:
for (i = 0; i < data.length; i += 1) {
myDataBase.executeSql("INSERT INTO LOGS (id, log) VALUES ("+i+", "+data[i]+")");
}
Here's the rest of the methods
myDataBase.init(); // uses set/default config
myDataBase.initWithConfig(shortName, version, displayName, maxSize);
myDataBase.executeSql(SqlCmmndString);
myDataBase.executeSqlWithCallBack(SqlCmmndString,SuccessCallbackfunction); // how you get data out
myDataBase.setInitConfig(shortName, version, displayName, maxSize);
This is the class code:
var DataBaseCtrl = function () {
if (!(this instanceof DataBaseCtrl)) {
return new DataBaseCtrl();
}
// Transaction error callback
function errorCB(tx, err) {
console.log("Error processing SQL: " + tx + tx.code + tx.message);
}
function successCB(tx, err) {
}
return {
_DB: null,
_config: {
// Default configuration
_shortName: "DefaultDataBaseName",
_version: "1.0",
_displayName: "DisplayName",
_maxSize: 65535 // in MBs
},
/* Initializer */
init: function () {
if (!window.openDatabase) {
alert("Databases are not supported on this device. \n\n ");
return false;
}
var cfg = {
shrt: this._config._shortName,
vers: this._config._version,
disp: this._config._displayName,
mxSz: this._config._maxSize
};
// Initialize the DataBase.
this._DB = window.openDatabase(cfg.shrt, cfg.vers, cfg.disp, cfg.mxSz);
},
/* Initialize with custom config */
initWithConfig: function (shortName, version, displayName, maxSize) {
this.setInitConfig(shortName, version, displayName, maxSize);
this.init();
},
/* Execute SQL command */
executeSql: function (SqlCmmnd) {
this._DB.transaction(function (tx) {
console.log("Executing SQL... " + SqlCmmnd.substring(0, 100));
tx.executeSql(SqlCmmnd);
}, errorCB, successCB);
},
/* Execute SQL with success callback */
executeSqlWithCallBack: function (SqlCmmnd, SuccessCallback) {
this._DB.transaction(function (tx) {
console.log("Executing SQL... " + SqlCmmnd.substring(0, 100));
tx.executeSql(SqlCmmnd, [], SuccessCallback);
}, errorCB, successCB);
},
/* Sets init config (call before initializing) */
setInitConfig: function (shortName, version, displayName, maxSize) {
console.log("Setting DB Config: " + displayName);
this._config = {
_shortName: shortName,
_version: version,
_displayName: displayName,
_maxSize: maxSize
};
}
};
};
Use an array to store the data from the JSON import. Then save the array to local storage.
$.ajax({
url: 'http://172.18.75.156/deals.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
var ArrayName = [];
$.each(data, function(i,item){
output.text('successful');
ArrayName[i] = item;
});
localStorage.setItem("jsontable",ArrayName);
},
error: function(){
output.text('There was an error loading the data.');
}
});
Then you can call that array using localStorage.GetItem("jsontable");
Then the user will be able to use the imported json table array without having to reimport.
I would suggest you to convert the object to string then save it in the localStorage.
To retrieve data, get the string from localStorage and convert it into JSON object
HTML5 localStorage
Related
I am not getting what's happening with my codes. I don't know why I am getting No. of '?'s in statement string doesn't match arguement count while I am not using '?' to insert values. Here is my code:
db = window.openDatabase("myDB", "1.0", "Test DB", 2000000);
db.transaction(populateDB, errorCB, successCB);
$.ajax({
type: 'POST',
url: "MY_SERVER_URL",
data: {"email": email, "password": password},
success: function (response) {
db.transaction(function (tx) { saveDetailsInDB(tx, JSON.stringify(response)) } ,errorCB , successInsertion);
},
error: function (errorMessage) {
window.alert("Something went wrong!");
}
});
}
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS UserDetailsInJSONform');
tx.executeSql('CREATE TABLE IF NOT EXISTS UserDetailsInJSONform (ID INTEGER, JSONdetails TEXT)');
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")');
}
function saveDetailsInDB(tx, response){
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")',done,errorCB);
}
function done(tx) {
alert("success ");
tx.executeSql('SELECT * FROM UserDetailsInJSONform', [], querySuccess, errorCB);
}
// Transaction error callback
function errorCB(err) {
alert("Error processing SQL: "+err.code+" "+err.message);
}
// Transaction success callback
function successCB() {
alert("Positive successCB");
}
function successInsertion() {
alert("Positive successInsertion");
}
function querySuccess(tx,results){
var len = results.rows.length;
alert("Row no. "+len);
for (var i=0; i<len; i++){
alert(results.rows.item(i).ID);
alert(results.rows.item(i).JSONdetails );
}
}
I am beginner in Phonegap. I tried to save my returned data from server in local SQLite DB. But I don't know why I am getting unknown errors. Please Help me !!
2nd argument in tx.executeSql expects values between brackets.
tx.executeSql(sqlToExecuteForTx,bracketValuesForTx,success,error);
In your code:
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")',done,errorCB);
It has 'done' as second value which refers to a function in your code. I would recommand to use:
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (?,?)',[1,"asd"],done,errorCB);
I am working with intel XDK and there I have a prepopulated .db file which i need to read inside my code. As we do in native app where we put db files in assets directory and then access those database by copying them in app's database directory. I am new to hybrid apps.
NB: For view DB created by your project ,
1st take a windows build and run your project .
Then go to
C:\Users\XXXXX\AppData\Local\Packages\pakagename\LocalState\yourdbname.db
You can find your DB file
you can view that file on this site
For database creation and usage
Please use the link to the Intel XDK third party plugin. Before that please download the project dependency jar file from GitHub and create the directory with Cordova plugin SQLite name and place the file in it, include the jar file. Then try to add the plugin using URL .
See the whole code below
1.create database
2.add table
3.add data to table
4.get data from table
> // Wait for Cordova to load
document.addEventListener('deviceready', onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
////////////////////////////////////////////////////////////////////////////////////////////////
alert("Start ");
var db = window.sqlitePlugin.openDatabase({ name: 'my.db', location: 'default' }, function () {
alert("database creatred");
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE customerAccounts (firstname, lastname, acctNo)');
alert("Table create");
addItem("first", "last", 100);
getData("last");
}, function (error) {
alert('transaction error: ' + error.message);
}, function () {
alert('transaction ok');
});
}, function (error) {
});
////////////////////////////////////////////////////////////////////////////////////////////////
function addItem(first, last, acctNum) {
alert("start adding");
db.transaction(function (tx) {
var query = "INSERT INTO customerAccounts (firstname, lastname, acctNo) VALUES (?,?,?)";
alert("start insterting");
tx.executeSql(query, [first, last, acctNum], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
alert("insert complete");
},
function(tx, error) {
alert('INSERT error: ' + error.message);
});
}, function(error) {
alert('transaction error: ' + error.message);
}, function() {
alert('transaction ok');
});
}
////////////////////////////////////////////////////////////////////////////////////////////////
function getData(last) {
db.transaction(function (tx) {
alert("get data");
var query = "SELECT firstname, lastname, acctNo FROM customerAccounts WHERE lastname = ?";
alert("get data working");
tx.executeSql(query, [last], function (tx, resultSet) {
for(var x = 0; x < resultSet.rows.length; x++) {
alert("First name: " + resultSet.rows.item(x).firstname +
", Acct: " + resultSet.rows.item(x).acctNo);
}
},
function (tx, error) {
alert('SELECT error: ' + error.message);
});
}, function (error) {
alert('transaction error: ' + error.message);
}, function () {
alert('transaction ok');
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////
}
I did it with sql.js and xml http request using following piece of code:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'yourDBname.db', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e)
{
mId = sessionStorage.i;
var uInt8Array = new Uint8Array(this.response);
var db = new SQL.Database(uInt8Array);
var contents = db.exec("SELECT * FROM ....your query");
// Do as per requirment
}
I m developing Android application. I'm integrating the sqlite into my application https://github.com/brodyspark/PhoneGap-sqlitePlugin-Android
The below error is coming
Uncaught TypeError: Object # has no method 'exec'
while using the following code
window.sqlitePlugin.openDatabase({name: "DB"});
You need to ensure you have waited for Cordova to load prior to opening a database.
As per the README.md from the project:
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
// ...
}
https://github.com/xuexueMaGicK/Gift-App
see this link js file is available here database connection are there
window.addEventListener("DOMContentLoaded", init);
function init() {
pageshow = document.createEvent("Event");
pageshow.initEvent("pageshow", true, true);
tap = document.createEvent("Event");
tap.initEvent("tap", true, true);
pages = document.querySelectorAll('[data-role="page"]');
numPages = pages.length;
links = document.querySelectorAll('[data-role="link"]');
numLinks = links.length;
//checkDB();
document.addEventListener("deviceready", checkDB, false);
}
/*******************************
General Interactions
*******************************/
function checkDB() {
navigator.splashscreen.hide();
database = openDatabase('data', '', 'data', 1024 * 1024);
if (database.version === '') {
database.changeVersion('', '1.0', createDB, function (tx, err) {
console.log(err.message);
}, function (tx, rs) {
console.log("Increment transaction success.");
});
addNavHandlers();
} else {
addNavHandlers();
}
}
function createDB(db)
{
/*******Create Table Gifts********/
db.executeSql('CREATE TABLE "gifts" ("gift_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_id" INTEGER, "occasion_id" INTEGER, "gift_idea" VARCHAR(45))', [], function (tx, rs) {
console.log("Table gifts created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Names********/
db.executeSql('CREATE TABLE "names" ("name_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table names created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Occasions********/
db.executeSql('CREATE TABLE "occasions" ("occasion_id" INTEGER PRIMARY KEY AUTOINCREMENT, "occasion_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table occasions created");
}, function (tx, err) {
console.log(err.message);
});
}
In Manifest.xml u have to add plugins related to the SQLite.Then it will work.
How to retrieve device id/ token at device registration? I am using Phonegap Pushwoosh example and it works fine. But I could not figure out how to retrieve the token at device registration initPushwoosh.
I am not a professional programmer. Any help will be appreciated.
I have an index.html that initialize
<body onload="init();">
In main.js
function init() {
document.addEventListener("deviceready", deviceInfo, true);
document.addEventListener("deviceready", initPushwoosh, true);
}
In PushNotification.js
function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
// CHANGE projectid & appid
pushNotification.registerDevice({ projectid: "xxxxxxx", appid : "xxxxxxxx" },
function(status) {
var pushToken = status;
console.warn('push token: ' + pushToken);
},
function(status) {
console.warn(JSON.stringify(['failed to register ', status]));
});
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
navigator.notification.alert(title);
});
}
The first section is the .registerDevice and the token is probably pushToken, but I just cannot figure out how to retrieve it from this function!
The best is to send it to a MySQL database lets call it smartphonedb.tokentable
I modified the initPushwoosh() to send me the token to MySQL using Ajax (see below) I am receiving nothing on MySQL. Am I sending the right Token param (pushToken)?
function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
// CHANGE projectid & appid
pushNotification.registerDevice({ projectid: "xxxxxx", appid : "xxxxxxx" },
function(status) {
var pushToken = status;
console.warn('push token: ' + pushToken);
// start my ajax to insert token to mysql
var param ={Token: pushToken};
$.ajax({
url: 'http://luxurylebanon.com/offeratlive/apitoken.php', data: param, dataType: 'json', success: function(result)
{
if(result.success == false)
{
alert(failed)
}
else {
alert(success)
}
}
});
// end ajax
},
function(status) {
console.warn(JSON.stringify(['failed to register ', status]));
});
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
navigator.notification.alert(title);
});
}
The PHP apitoken.php
<?php
$username="xxxxxxx";
$password="xxxxxxxxxxxx";
$database="offeratdb";
$server="offeratdb.db.xxxxxxxxx.com";
$connect = mysql_connect($server,$username,$password)or die('Could not connect: ' . mysql_error());
#mysql_select_db($database) or die('Could not select database ('.$database.') because of : '.mysql_error());
$vtoken= $_POST['Token'];
// Performing SQL query
$query = "INSERT INTO `tokentable` (`thetoken`) VALUES ('$vtoken')";
$result = mysql_query($query)or die('Query failed: ' . mysql_error());
echo $vtoken;
// We will free the resultset...
mysql_free_result($result);
// Now we close the connection...
mysql_close($connect);
?>
any help will be appreciated
After looking through your code I think it contains some mistakes.
So, lets try to fix them:
First of all. Do you have jquery js script included before PushNotification.js? If not, "$.ajax" will not be executed.
The other thing. The ajax default type is GET, and you use POST in your php code.
And you don't use json at all. So your code should be transformed into something like this
$.ajax({
type: "POST",
async: true,
url: url,
data: params,
success: function (result) {
// todo
},
error: function (result) {
// todo
}
});
And the last thing. The param var should be initialized like this:
var param = "Token="+pushToken;
Hope this would be helpful.
I was having the same problem, I updated the Pushwoosh.jar and it worked for me. :)
I'm working an android application that is wrapped using phonegap and I'm using its Storage API. How can I pass an argument on my Sqlite Query to get a specific row? Thanks in advance. Below is my script. Can you provide me an example? Thanks
$(document).ready(function() {
code = 1;
var db = window.openDatabase("DEMO", "1.0", "DEMOX", 20000000 ); // 20MB in quuota storage size
db.transaction(function(){ queryDB(code) }, errorCB, querySuccess);
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 (!resultSet.rowsAffected) {
alert('No rows affected!');
return false;
}
}
function queryDB(tx, code) {
tx.executeSql('SELECT * FROM table WHERE code = ?', [code], querySuccess, errorCB);
}
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
});
My solution : hope this will help others.
$(document).ready(function() {
code = 1;
var db = window.openDatabase("DEMO", "1.0", "DEMOX", 20000000 ); // 20MB in quuota storage size
db.transaction(queryDB, errorCB, querySuccess);
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 (!resultSet.rowsAffected) {
alert('No rows affected!');
return false;
}
}
function queryDB(tx) {
var sql = 'SELECT * FROM table WHERE code = :code';
tx.executeSql(sql, [code], querySuccess, errorCB);
}
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
});