I want to make an app with Phonegap, but I have problems with the Web SQL coding.
The app is very simple: button1 to pick current time and set on value1, then button1 pick current time again and set to value2; a field to identificate the activity and after all fields are filled, button1 again to open a dialog box to OBS, and then open a new page with all activities:
// JavaScript Documentvar db;
var dbCreated = false;
/*var scroll = new iScroll('wrapper', {
vScrollbar : false,
hScrollbar : false,
hScroll : false
}); */
document.addEventListener("deviceready", onDeviceReady, false);
var ativ = document.getElementById("ativ").value;
var hi = document.getElementById("hi").value;
var hf = document.getElementById("hf").value;
var obs = document.getElementById("obs").value;
function onDeviceReady() {
db = openDatabase("RegistrationDB", "1.0", "Registration", 1024 * 1024);
if (dbCreated) {
} else {
db.transaction(populateDB, transaction_error, populateDB_success);
}
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS RegistrationDB');
var sql = "CREATE TABLE IF NOT EXISTS RegistrationDB ( " + " atividade, " + " horaInicial, " + " horaFinal, " + " observacao)";
tx.executeSql(sql);
tx.executeSql("INSERT INTO RegistrationDB (atividade, horaInicial, horaFinal, observacao) VALUES ('" + ativ + "','" + hi + "' , " + hf + ", '" + obs + "')");
}
function transaction_error(tx, error) {
alert("Database Error: " + error);
}
function populateDB_success() {
dbCreated = true;
// where you want to move
alert("Successfully inserted");
window.location="tela2.html";
}// JavaScript Document
Related
I have some trouble with my js callback, I can't understand why my callback of my function don't want execute all the code, just to give you an idea :
class LogsPortail {
static SetLogs(pool, req, res, callback) {
console.log('start log ');
var bCallBack = false;
var now = new Date();
var endpoint = req.originalUrl
endpoint = endpoint.split("?")[0]
endpoint = endpoint.replace("/", "")
var query = "INSERT INTO LOGS_PORTAIL (ENDPOINT, TYPE, DATE_HEURE_LOGS, LOGIN) VALUE ('" + endpoint + "','" + req.method + "','" + now.toISOString().slice(0, 19).replace('T', ' ') + "','" + 'API' + "')";
var queryParam = "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ";
console.log('query 1 log ');
pool.query(query, function(err, results) {
if (err) {
console.log("Error : " + query);
bCallBack = true;
callback();
} else {
console.log('query log 2');
//On a bien inséré le logs portail, maintenant on ajout tous les paramètres
for (var key in req.query) {
if (queryParam != "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ")
queryParam += ","
queryParam += " (" + results.insertId + ",'" + key.toLowerCase() + "', '" + req.query[key] + "')"
}
for (var key in req.body) {
if (queryParam != "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ")
queryParam += ","
queryParam += " (" + results.insertId + ",'" + key.toLowerCase() + "', '" + req.body[key] + "')"
}
pool.query(queryParam, function(err, resultsParam) {
if (err) {
console.log("Error : " + queryParam);
console.log(err);
bCallBack = true;
callback();
} else {
bCallBack = true;
callback();
}
});
}
});
while (bCallBack === false) {}
console.log('call back end ');
//callback();
}
}
To explain you, my first query will be executed perfectly, and after that, the callback will not go through the condition but will go at the end where (for the test) I put an infinity while where my code will never exit.
This is what my log shows - we never see the logs "query log 2"
Thanks for your help
I've been trying to do this since a long time.
[PHANTOMJS VERSION] => 2.1.1
My goal is to log in a portal, go to different menu after being logged, insert parameters to research available file, download file if not downloaded yet.
Problem is that I can login to the portal and reach the index page but when I click on the tag "a" which is the one button that bring me to the new form to fill for searching file, it bring me back to loginpage ... Dunno why that happend. If I use this script in chrome dev it works fine ...
LOGIN SUCCESFUL
REDIRECTED TO LOGIN PAGE
This is my code:
<pre><code>var page = require('webpage').create();
var system= require('system');
var loadInProgress = false;
var testindex = 0;
var address;
var pos;
var stringa;
// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
});
}
console.error(msgStack.join('\n'));
};
page.onAlert = function(msg) {
console.log('alert!!> ' + msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("CARICAMENTO PAGINA INIZIATO"); //*Page started loading*
};
page.onLoadFinished = function(status) {
loadInProgress = false;
if (status !== 'success') {
console.log('Caricamento pagina fallito !'); //*Page failed to load*
phantom.exit();
} else {
console.log("CARICAMENTO PAGINA COMPLETATO"); //*Page loading complete*
page.render("foto" + testindex + ".png");//*Screen Capture*
console.log("Foto effettuata");
var sitoattuale= page.evaluate(function(){
return window.location.href;
});
console.log(sitoattuale);
}
};
var steps = [
function() {
page.open(system.args[1]);
},
function() {
page.evaluate(function() {
//*insert username and password and click the button to submit the form*
document.getElementById("twsTemplate_Content1_twsModule_txtUser").value="MYUSERNAME";
document.getElementById("twsTemplate_Content1_twsModule_txtPSW").value="MYPASSWORD";
document.getElementById("twsTemplate_Content1_twsModule_btnLogin").click();
});
//*Capture inserted credentials*
page.render("credenziali.png")
},
function() {
page.evaluate(function(){
var a=document.getElementById("twsTemplate_Header1_Mainmenu2_aspMainMenun16Items");
var b= a.getElementsByTagName("a");
var c= b[0];
c.click();
});
//*Capture click of the button that brings me to the form where I ve to insert parameters for the search*
page.render("Cliccato_ricerca.png")
},
function() {
//*I capture the screen as I should be to the form page but it caputre the login page unfilled*
page.render("ramomisura.png")
console.log("stouscendo");
}
];interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
if (testindex==0){
console.log("Fase " + (testindex+1) + " : Avvio portale");
}else{
if(testindex==1){
console.log("Fase " + (testindex+1) + " : Loing in corso ...");
}else{
if(testindex==2){
console.log("Fase " + (testindex+1) + " : Tentativo di navigazione al ramo misure ...")
}else{
console.log("Fase " + (testindex+1) + " : Termine Programma");
}
}
}
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("Programma Terminato");
phantom.exit();
}
}, 100)
</code></pre>
When i will save into my database "C'est tout à fait juste.", sqlite will remove the & from à, becouse it can't maybe handle utf-8.
var sql += "INSERT INTO Test(TestId,Text) Values(1, "C'est tout à fait juste.");
I tried for every insert to replace the $agrave with à, but I think there will be a better solution.
Is there a better way to solve this?
Thanks for any help...
UPDATE
This is my code to create my sqlite database:
function initDb($cordovaSQLite, logService) {
var defcorrect = $.Deferred();
try {
logger = logService;
db = window.sqlitePlugin.openDatabase({ name: "xxx.db", location: 0 }, successCB, errorCB);
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS Card(CardId UNIQUEIDENTIFIER PRIMARY KEY, CardSetId UNIQUEIDENTIFIER NOT NULL, FrontText NVARCHAR(4000) NOT NULL, BackText NVARCHAR(4000) NULL, ControlType INT NOT NULL, CardLevel INT NOT NULL, IsDirty bit NOT NULL, ChangedAt INT NOT NULL, Active bit default 'true')").catch(function (err) {
logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init Table Card: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message);
window.location = "#/error/" + startGUIDLog;
});
$cordovaSQLite.execute(db, "CREATE UNIQUE INDEX IF NOT EXISTS Card_Index on Card (CardId)").catch(function (err) {
logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init INDEX Card_Index on Card: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message);
window.location = "#/error/" + startGUIDLog;
});
defcorrect.resolve(db);
} catch (err) {
logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init Database: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message);
window.location = "#/error/" + startGUIDLog;
}
return defcorrect.promise();
}
And with this code I insert the data
function saveCard(cardList, userId, db) {
var defcorrect = $.Deferred();
truncateTable("Card", db, userId).done(function () {
if (cardList.length !== 0) {
var sql = "";
cardList.forEach(function (card) {
sql += "INSERT INTO Card(CardId,CardSetId,FrontText,BackText,ControlType,CardLevel,IsDirty,ChangedAt,Active) VALUES (" + JSON.stringify(card.CardId) + "," + JSON.stringify(card.CardSetId) + "," + JSON.stringify(Card.FrontText) + "," + JSON.stringify(Card.BackText) + "," + card.ControlType + ", " + card.CardLevel + ",'" + card.IsDirty + "'," + card.ChangedAt + ",'" + card.Active + "');";
});
var successFn = function (count) {
logService.writeAppInfo(userId, "Sync Save Card Successfully imported " + count + " SQL statements to DB");
defcorrect.resolve();
};
var errorFn = function (error) {
logService.writeAppError(userId, "Sync Save Card Error: " + error);
$('#statusOverview').hide();
$('#syncError').show();
};
var progressFn = function (current, total) {
$("#statusText").text("Importiere " + current + "/" + total + " Karten");
};
cordova.plugins.sqlitePorter.importSqlToDb(db, sql, {
successFn: successFn,
errorFn: errorFn,
progressFn: progressFn,
batchInsertSize: 500
});
} else {
defcorrect.resolve();
}
});
return defcorrect.promise();
}
In the debug mode I can see, that the data comes in the right way like "C'est tout à fait juste." and after insert when i read out this data it comes like this: "C'est toutagrave; fait juste."
For me this solution worked:
var elemfolderName = document.createElement('textarea');
elemfolderName.innerHTML = "C'est tout à fait juste.";
var folderName = elemfolderName.value;
And then I save folderName to sqlite3 db...
I am attempting to do a small PoC with PDFs and have run into an issue. I am looking to post a message to a PDF and have the PDF post a message to the browser.
The deets:
I am viewing the PDF in an "object" element in IE9. I am using itextsharp to prefill a pdf template on the server, inject some app level javascript (post message and on message stuff) and then serve that up to the browser via a filestreamresult. I am using Reader 10 to view the PDF in IE9.
What works:
So far, everything works except for the PDF posting a message to the browser. I can post a message to the PDF, from the browser, no problem and all of the fields are prefilled as desired.
What doesn't work:
When I try using this.hostContainer.postMessage(["something","somethingmore"]) I get an Acrobat Escript window that says "hostContainer is not defined". I have also tried using "event.target.hostContainer" but I get "event.target is not defined". I am at a loss of what to do and any insight would be super helpful.
Reference links:
Acrobat Javascript API
Stackoverflow How-To on this topic
Original guide I used
The code:
My form view:
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
My custom javascript string method:
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(doc.xfa);" +
"console.println('Doc xfa value = ' + doc.xfa);" +
// "event.target.hostContainer.postMessage(['hello from pdf!']);" +
// "this.hostContainer.postMessage(['hello from pdf!']);"+
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
My method for filling and sending the form to the browser:
public MemoryStream GetFilledRequestForm(string fileDirectory, User user, FormView formView)
{
var pdfStream = new MemoryStream();
var templateFilePath = GetRequestTypeTemplateFilePath(fileDirectory, _requestModule.FormTemplateFileName);
var pdfReader = new PdfReader(templateFilePath);
// pdfReader.RemoveUsageRights();
var stamper = new PdfStamper(pdfReader, pdfStream);
var formFields = GetFormFields(user, formView, pdfReader);
foreach (var field in formFields.Where(f => f.Value != null))
{
stamper.AcroFields.SetField(field.Name, field.Value);
}
stamper.FormFlattening = false;
var newJs = GetCustomJavascript(stamper.Reader.JavaScript);
stamper.AddJavaScript("newJs", newJs);
stamper.Close();
byte[] byteInfo = pdfStream.ToArray();
var outputStream = new MemoryStream();
outputStream.Write(byteInfo, 0, byteInfo.Length);
outputStream.Position = 0;
return outputStream;
}
Ok, so I have resolved it, with some help of course. I found the key at this stack overflow post. I needed to wait for the object to load before assigning the message handler. Additionally, I needed a global variable in the pdf javascript to be able to post the message.
Html/Javascript: (the key here is the loadListener() function)
#model WebModel.FormView
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
<input id="buttonPost" type="button" value="post to pdf"/>
<script type="text/javascript">
var PDFObject = document.getElementById("pdfFrame");
function loadListener() {
if (typeof PDFObject.readyState === 'undefined') { // ready state only works for IE, which is good because we only need to do this for IE because IE sucks in the first place
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
return;
}
if (PDFObject.readyState == 4) {
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
} else {
setTimeout(loadListener, 500);
}
}
function messageFunc(data) {
debugger;
var messagedata = data;
alert('finally!!');
}
function sendToPdf() {
if(PDFObject!= null){
PDFObject.postMessage(
["a", "b"]);
}
}
$('#pdfFrame').ready(function() {
loadListener();
$('#buttonPost').on('click', function() {
sendToPdf();
});
});
</script>
My new function to create the javascript: (the key here is var appHostContainer)
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"var appHostContainer = this.hostContainer;" +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(stringArray);" +
"appHostContainer.postMessage(['hello from pdf!']);" +
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
** i'm developing a phonegap application but it cannot connect the database i attached the following program? my code is below:**
function onDeviceReady() {
var mobno = document.getElementById("mobno").value;
var cust = document.getElementById("cust").value;
db = window.openDatabase("RegistrationDB", "1.0", "Registration", 200000);
if (dbCreated)
else
db.transaction(populateDB, transaction_error, populateDB_success);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS Registration');
var sql = "CREATE TABLE IF NOT EXISTS Registration ( "
+ "mobno INTEGER(50), " + "custname VARCHAR(50))";
tx.executeSql(sql);
var mobno = document.getElementById("mobno").value;
var cust = document.getElementById("cust").value;
tx.executeSql("INSERT INTO Registration (mobno,custname) VALUES ('"+ mobno +"','"+ cust +"')");
}
function transaction_error(tx, error) {
alert("Database Error: " + error);
}
function populateDB_success() {
dbCreated = true;
// where you want to move
alert("Successfully inserted");
window.location="file:///android_asset/www/login.html";
}
If you would like to use the Cordova SqlLite plugin you have to install it:
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin
next you can create the db in device ready:
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
}