Chrome Deleting WebSQL Database Between Requets - javascript

So i'm trying to create an offline app with AngularJS as the front-end and Play! 1.2.5 as the back-end. On the client side, I created 2 pages - main.html and login.html where upon submitting the form on login.html, a WebSQL database is created
var db = openDatabase("users", "1.0", "User Database", 2*1024*1024
some data is added in and the user is forwarded to main.html.
The problem is that when I call
var db = openDatabase("users", "1.0", "User Database", 2*1024*1024);
on main.html, I get the database but with none of the information created on the login.html page. What is going on here?
EDIT: Here's some code
login.html (JavaScript section):
var db = window.openDatabase("myDB", "1.0", "Example Database", 2*1024*1024);
db.transaction(function(tx) {
tx.executeSql("drop table if exists users");
tx.executeSql("create table users (id unique, name)");
tx.executeSql("insert into users (id, name) values (?, ?)", [1, "Kevin"]);
});
main.html:
var db = window.openDatabase("myDB", "1.0", "Example Database", 2*1024*1024);
db.transaction(function(tx) {
tx.executeSql("select * from users", [], function(tx, results) {
for(i=0; i<results.rows.length; i++) {
var u = {
id: results.rows.item(i).id,
name: results.rows.item(i).name,
}
console.log(u); //Nothing gets returned. Database in Resources tab is empty; no users!
}
});
});
The database I created in index.html shows up, but the User data I entered isn't there. I'm using the default Play! development web server. This problem does not occur when i'm using LightTPD, but then of course I can't access my Play! application DB due to Access-Control-Origin stuff.

I think your are getting to the main.html before the inserts can execute. Remember that WebSQL API is asynchronous, so when your code sends the transaction to drop/create/insert your app won't wait and goes straight for the main.html (if your are not using the callback to change the page).
What you have to do is send the transaction and wait for the callback (onSuccessSql) to change to the main.html. here is an example:
db.transaction(function(tx){
tx.executeSql( "insert into users (id, name)...", onSuccessSql, onError)},
onError, onReadyTransaction);
function onReadyTransaction( ){
console.log( 'Transaction completed' )
}
function onSuccessSql( tx, results ){
//go to main.html()
}
function onError( err ){
console.log( err )
}

Related

Alerting users on website through ajax

I'm attempting to make a notification system that notifies users when they are assigned to a ticket, or when a new ticket is added to the database.
The system itself, that I already have, works except that it only sends the notification to the first user who receives the ajax request. Is there any way to make it so that everyone who is suppose to receive the notification, actually receives the notification?
My code:
javascript:
function checkUpdates()
{
$.ajax({
type: "POST",
url: 'ajax/checkDB.php', // a webservice or other URL that queries the database
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log('Connected and executed PHP page... '+data);
if (data.hasChanged == "true") {
playSound('img/notif2');
notifyAdmin();
console.log('Updated Tickets Page...');
$("#contents").load("dynamic/tickets.php");
$("#contents").fadeTo("fast", 1);
}
if (data.newAssigned == "true") {
playSound('img/notif2');
notifyUser();
console.log('Updated Tickets Page...');
$("#contents").load("dynamic/tickets.php");
$("#contents").fadeTo("fast", 1);
}
}
});
}
$(document).ready(function() {
setInterval("checkUpdates()", 3000); // Calls the function every 3 seconds
});
My php script (checkDB.php):
<?php
include("../static/config.php");
session_start();
header("Content-Type: text/json");
$result = mysqli_query($con,"SELECT notify FROM tickets WHERE notify='0'");
$row_cnt = mysqli_num_rows($result);
if($row_cnt > 0) {
$hasChanged = 'true';
mysqli_query($con,"UPDATE tickets SET notify='1' WHERE notify='0'");
} else {
$hasChanged = 'false';
}
$result2 = mysqli_query($con,"SELECT notify,Assigned FROM tickets WHERE Completeness='1' AND notify='1'");
$row_cnt2 = mysqli_num_rows($result2);
if($row_cnt2 > 0) {
while($row2 = mysqli_fetch_array($result2))
{
if(strcmp($_SESSION['Name'],$row2['Assigned']) == 0) {
$newAssigned = 'true';
} else {
$newAssigned = 'false';
}
}
mysqli_query($con,"UPDATE tickets SET notify='2' WHERE Completeness='1' AND notify='1'");
} else {
$newAssigned = 'false';
}
echo json_encode(array('newAssigned' => $newAssigned, 'hasChanged' => $hasChanged));
?>
Here is a rundown of my exact intentions:
User logs into system, and is given administrative rights if granted.
User loads the tickets page, which lists all the tickets along with this javascript that I gave you
the javascript loads checkDB.php every 3 seconds, basically running a check against the database for a 'notify' value of 0, and if at least 1 exists, is updated in the database to '1' and is returned as true to the ajax call - which sends out notifications.
Again this works for the 1st user who is loaded into the page, but after that, obviously there are no more 'notify=0' in the database as they have already been updated, so they are not shown the notification.
It was requested that I share my database structures.
tickets:
UniqueID - Unique ID per ticket (always unique)
Requester - Whoever submitted the ticket.
Problem - Description of the given issue.
Assigned - User who is assigned to the ticket.
Completeness - The level of completeness (0-4)
Times - Times listed for ticket start, assigned, etc
notified - Used in old ticket system (I plan to get rid of it)
Urgency - Selected by requester, how urgent the ticket is
Location - Location in our warehouse assistance is needed.
FollowUp - currently not in use, will be used to submit follow ups.
isProject - (0-1) is project or not
additionalTechs - Lists additional users on a ticket (Not important for question)
notify - (0-2) at 0, ticket is new and notif should be sent to admins which should set this to 1, when it is 1 it should send a notif to users that are attached to the ticket.
Techs Database:
UniqueID
Username
Password
Name
Level
Disabled
LastTimeSeen
needsNotify (Used in old system, plan to remove)
I'm really stuck here.
You can make it with websockets, or socket.io.
Then the js of multiple clients will connect with that socket will notify all connected people about they ticket
You can change your update statement to something like:
UPDATE tickets SET notify='1' WHERE notify='0' and Assigned = ''//some user id passed

Database and local Storage get cleared in IOS phonegap application

About App -
I am using corodova 2.1.0 in ios phonegap application.
My app does some registration process in that it checks if the app is registered or not if it found data in database or local storage it goes to dashboard else it ask for registration.
In registration process app ask for mobile no if mobile entry from back end is fond then app will download data from database and stores it in localstorage and database.
Issue-
if is give registered for first time app downloads data and goes to dashboard. and if i kill the app and then open it it will ask for registration and if i registered second time and after going on dashboard if i kill app and open again app then it will shows dasboard afterwords it donesn't show registration screen.
I checked on weinre first time also it loads all data in database and local sotrage.
i am storing only name and user's id. but it get cleared if i kill app after first installation.
//Here is code which checks that user is registred or not
// this will ckeck on splashscrenn
//$window.location.href = '#/SplashScreen';
function checkregistration(){
var sqlU = 'SELECT ClubId, MemberId, MemberName FROM member_master_dtls';
var obj = {};
var db = window.openDatabase("ROW_DB", "", "Cordova Demo", 200000);
try{
var MID = localStorage.getItem('MyMemberID');
console.log("MID befo "+ typeof(MID));
console.log("MID === "+ (MID));
if ( MID.length>0)
{
console.log("MID"+ MID);
RowDbService.CheckVersion();
$window.location.href = '#/Dashboard';
}else{
db.transaction(function(tx) {
//console.log('in db trans');
tx.executeSql(sqlU, [], SuccessChkMemlst_local, errorCB);
});
}
}
catch(err){
db.transaction(function(tx) {
//console.log('in db trans');
tx.executeSql(sqlU, [], SuccessChkMemlst_local, errorCB);
});
}
}
function SuccessChkMemlst_local(tx, results) {
//alert("success splash");
//console.log("successlist = " + results.rows.length);
if (results.rows.length == 0) {
//localStorage.setItem('globalx', '1');
globalx = 1;
$window.location.href = '#/Register';
//console.log(results);
} else {
RowDbService.CheckVersion();
$window.location.href = '#/Dashboard';
}
}
=================================
//here is function on Register page that download data from webservice and store it in database
//$window.location.href = '#/Register';
function ChkForRegistration(){
//here some webservices wich downloads th
localStorage.setItem('ClubID', obj[0].ClubId);
localStorage.setItem('MyMemberName', obj[0].member_name);
localStorage.setItem('MyMemberID', obj[0].member_master_id);
localStorage.setItem('MyClubName', obj[0].club_name);
localStorage.setItem('NewsCount',0);
localStorage.setItem('AnnCount',0);
localStorage.setItem('EventCount',0);
localStorage.setItem('BdayCount',0);
localStorage.setItem('EventDate',"");
localStorage.setItem('BdayDate',"");
var datarow = {};
datarow.MemberId = localStorage.getItem('MyMemberID');
datarow.MemberName = localStorage.getItem('MyMemberName');
datarow.ClubId = localStorage.getItem('ClubID');
datarow.ClsfyName = localStorage.getItem('MyClubName');
var db = window.openDatabase("ROW_DB", "", "Cordova Demo", 200000);
db.transaction(function(tx) {
var query="insert into member_master_dtls (id,MemberId,MemberName,ClubId,ClsfyName) values(?,?,?,?,?)";
tx.executeSql("update sqlite_sequence set seq = 0 where name ='member_master_dtls'");
tx.executeSql("delete from member_master_dtls");
tx.executeSql(query,[(1),datarow.MemberId,datarow.MemberName,datarow.ClubId,datarow.ClsfyName]);
tx.executeSql("update sqlite_sequence set seq =1 where name ='member_master_dtls'");
});
$window.location.href = '#/Dashboard';
}

How can i send maill with mailchimp template and add own text in node.js

So I'm using node.js and i installed modulem ailchimp-api (https://npmjs.org/package/mailchimp-api) so i went to offical website to read how to send mailchimp email and i figured out standard procedure.
var MailChimpAPI = require('mailchimp').MailChimpAPI;
var apiKey = 'Your MailChimpAPI API Key';
try {
var api = new MailChimpAPI(apiKey, { version : '2.0' });
} catch (error) {
console.log(error.message);
}
api.call('campaigns', 'list', { start: 0, limit: 25 }, function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});
api.call('campaigns', 'template-content', { cid: '/* CAMPAIGN ID */' }, function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});
I run on next problem ! How can I add my own text to the exsisting template in mailchimp ? I can choose campaign .. and write text ( on the web site of mailchimp ) but I wanted to send a confirmation link to the template but I dont figure out how can I do ...
maybee is some way to define the area where can i put text ? or should i copy entire html code and style from mailchimp and then put between the text the url link for confirmation ( not for subscription but for validation of user.
Thx for anwsers!
I got it.
If you don't have list in mailchimp, create it.
Go to settings in list and pick "List fields" and "|MERGE|" tags.
Add new field (field label, field type, required, visible, put this tag in your content) (I put under tag "ACTIVATED")
Add this tag to the template. You find it under text editor tab "Merge Tags".
In node.js, call function mc.lists.subscribe(data, function(data)).

Check a Boolean value from database at the start of an app then load terms and condition page if false, load menu page if true

Is this possible?
Before any page loads, could I run JavaScript code to check what the value in a database is, then open the relevant page?
Here is my code so far:
function onDeviceReady() //Phone gap is ready
{
try
{
db = openDatabase('cuopioid', '1.0', 'cupioids application database',
2 * 1024 * 1024);
} catch (e)
{
// Error handling code goes here.
if (e == INVALID_STATE_ERR)
{
// Version number mismatch.
alert("Invalid database version.");
}
else
{
alert("Unknown error " + e + ".");
}
}
console.log("DATABASE Created!");
db.transaction(createTableTerms, errCB, console.log("MEDICINES Table Created!"));
$('#btnaccept').on('click', acceptTerms);
}
The code below creates the database (if it isn't there already)
function createTableTerms(tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS TERMS (id unique, status boolean)');
tx.executeSql('INSERT INTO TERMS (id, status) VALUES (0, 0)');
console.log("TERMS Table Created!");
}
I have created this function which selects the rows form the database if it is set to true, then if the results has 1 record I want it to open the menu page, if it has no results it means the terms and conditions haven't been accepted previously:
function checkTerms(tx)
{
db.transaction(function(tx)
{
tx.executeSql('SELECT * FROM TERMS WHERE status=1', [],console.log("check terms"), errCB);
});
var len = results.rows.length;
if (len = 1)
{
console.log("accepted previously - menu page");
}
else
{
console.log("termsandconditions page");
}
}
I am not sure where to put this checkTerms(tx) function
I solved this problem by creating a new JavaScript file which runs when a html page lodes (start of the <head> tag
Which opens the database
Runs the SQL query to find the value
Opens the relevant page depending on the result
It still displays the page (half a second at most) when I load the page, but it does what I want
Here is the code:
try
{
db = openDatabase('cuopioid', '1.0', 'cupioids application database',
2 * 1024 * 1024);
} catch (e)
{
// Error handling code goes here.
if (e == INVALID_STATE_ERR)
{
// Version number mismatch.
alert("Invalid database version.");
}
else
{
alert("Unknown error " + e + ".");
}
}
checkTerms();
function checkTerms(tx)
{
db.transaction(function(tx)
{
tx.executeSql('SELECT * FROM TERMS WHERE status=1', [], openPage, errCB);
});
}
function openPage(tx, results)
{
var len = results.rows.length;
if (len = 1)
{
getDrugs();
window.location.href = "#page1"
console.log("accepted previously - menu page");
}
else
{
window.location.href = "#page0"
console.log("termsandconditions page");
}
}
Another way to solve this may of been to write a php page as kind of a clearing house based on your database values, then redirect the user to the relevent page. You could do this with ajax and the user wouldn't momentarily see the wrong page either.

Accessing pre-populated table on Android, getting error "No such table: TableName"

I have a prepopulated database that resides in my assets folder and is copied to my /data/data/com.package/database folder when downloaded to the emulator. I am trying to access this database via Phonegap sql calls. I have checked that the table is correctly being ported to the emulator and all of the data is correct. I keep getting an error of table not found however. I am pretty new to app dev so this could be an easy fix. Thanks.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("careerDB.db", "", "Career DB", 60416);
var careers;
errorHandler = function(){
$('#careerList').append('Error!');
}
db.transaction(getCareerList);
function getCareerList(transaction){
transaction.executeSql('SELECT * FROM Careers',[], function(transaction, results) {
$('#careerList li').remove();
for(var i=0;i<results.rows.length;i++){
var row = results.rows.item(i);
$('#careerList').append('<li><h4>' + row['career'] + '</h4></li>');
}
$('#careerList').listview('refresh');
},errorHandler);
}
}

Categories