Web Database - tx.executeSql callback not running every time - html

I have an HTML5 website built using jQuery Mobile.
On my index.htm page I have an ahref. When I click on that link I run a function which does a tx.executeSql and the callback method is run which then navigates to the new page.
The works fine the first time.
If I navigate to more pages and then come back to the index.htm page, the functions are run when the link is clicked, however the callback on the tx.executeSql isn't ever run.
Any ideas would be greatly appreciated. I have used all different mechanisms for calling the functions from javascript to jquery, but it makes no difference.
To be clear - the first function called is setFeaturedRecruiter() - you can see the code below. The second time I come back here the "renderResults" callback function isn't run.
// when we click on the actual featured recruiter link we copy from this table to the featured recruiter table to overwrite its contents
function setFeaturedRecruiter() {
alert('setFeaturedRecruiter()');
retrieveActualFeaturedRecruiter();
return true;
}
function retrieveActualFeaturedRecruiter() {
alert('retrieveActualFeaturedRecruiter()');
db.transaction(function (tx) {
alert('select * from featuredRecruiterActual...');
tx.executeSql('SELECT * FROM featuredRecruiterActual', [], renderResults, pnetOnError);
});
}
pnetOnError = function (tx, e) {
alert('Something unexpected happened: ' + e.message);
}
function renderResults(tx, rs) {
alert('renderResults()');
var idNo;
var name;
var logo;
var totalAds;
for (var i = 0; i < rs.rows.length; i++) {
r = rs.rows.item(i);
idNo = r.idNo * 1;
name = r.name;
logo = r.logo;
totalAds = r.totalAds;
}
writeToFeaturedRecruiter(idNo, name, logo, totalAds);
}

I've worked around this problem by disabling ajax when navigating between pages. This was done by adding to the ahref tag: data-ajax="false". This caused the page to load correctly and overcomes the problem.

Related

Repeatedly Grab DOM in Chrome Extension

I'm trying to teach myself how to write Chrome extensions and ran into a snag when I realized that my jQuery was breaking because it was getting information from the extension page itself and not the tab's current page like I had expected.
Quick summary, my sample extension will refresh the page every x seconds, look at the contents/DOM, and then do some stuff with it. The first and last parts are fine, but getting the DOM from the page that I'm on has proven very difficult, and the documentation hasn't been terribly helpful for me.
You can see the code that I have so far at these links:
Current manifest
Current js script
Current popup.html
If I want to have the ability to grab the DOM on each cycle of my setInterval call, what more needs to be done? I know that, for example, I'll need to have a content script. But do I also need to specify a background page in my manifest? Where do I need to call the content script within my extension? What's the easiest/best way to have it communicate with my current js file on each reload? Will my content script also be expecting me to use jQuery?
I know that these questions are basic and will seem trivial to me in retrospect, but they've really been a headache trying to explore completely on my own. Thanks in advance.
In order to access the web-pages DOM you'll need to programmatically inject some code into it (using chrome.tabs.executeScript()).
That said, although it is possible to grab the DOM as a string, pass it back to your popup, load it into a new element and look for what ever you want, this is a really bad approach (for various reasons).
The best option (in terms of efficiency and accuracy) is to do the processing in web-page itself and then pass just the results back to the popup. Note that in order to be able to inject code into a web-page, you have to include the corresponding host match pattern in your permissions property in manifest.
What I describe above can be achieved like this:
editorMarket.js
var refresherID = 0;
var currentID = 0;
$(document).ready(function(){
$('.start-button').click(function(){
oldGroupedHTML = null;
oldIndividualHTML = null;
chrome.tabs.query({ active: true }, function(tabs) {
if (tabs.length === 0) {
return;
}
currentID = tabs[0].id;
refresherID = setInterval(function() {
chrome.tabs.reload(currentID, { bypassCache: true }, function() {
chrome.tabs.executeScript(currentID, {
file: 'content.js',
runAt: 'document_idle',
allFrames: false
}, function(results) {
if (chrome.runtime.lastError) {
alert('ERROR:\n' + chrome.runtime.lastError.message);
return;
} else if (results.length === 0) {
alert('ERROR: No results !');
return;
}
var nIndyJobs = results[0].nIndyJobs;
var nGroupJobs = results[0].nGroupJobs;
$('.lt').text('Indy: ' + nIndyJobs + '; '
+ 'Grouped: ' + nGroupJobs);
});
});
}, 5000);
});
});
$('.stop-button').click(function(){
clearInterval(refresherID);
});
});
content.js:
(function() {
function getNumberOfIndividualJobs() {...}
function getNumberOfGroupedJobs() {...}
function comparator(grouped, individual) {
var IndyJobs = getNumberOfIndividualJobs();
var GroupJobs = getNumberOfGroupedJobs();
nIndyJobs = IndyJobs[1];
nGroupJobs = GroupJobs[1];
console.log(GroupJobs);
return {
nIndyJobs: nIndyJobs,
nGroupJobs: nGroupJobs
};
}
var currentGroupedHTML = $(".grouped_jobs").html();
var currentIndividualHTML = $(".individual_jobs").html();
var result = comparator(currentGroupedHTML, currentIndividualHTML);
return result;
})();

Can I develop an wizard application (sequentially submit forms)?

In my understanding now, only one doGet() can trigger unique doPost() in a Google Apps Script application.
I would like to perform a Software Publisher System that user upload the file or fill up revision information in forms and push submit to the next step. The final page will show the input information, send email to guys and complete all operation.
But how do I enter next form after the submit button pushed?
I have tried a method that creating the 2nd step and 3rd step forms in the doPost(), and using try...catch to difference which step form triggered the current step, like the following code.
(Because any steps can't get the callback item throw by non-previous step, then it arises an exception)
It works very well but I think it doesn't make sens and very silly. Have any better solutions? Thanks, please.
//---------------------------------------------------------------------------
function doGet(e)
{
var app = UiApp.createApplication().setTitle("AP Publisher");
createFileUploadForm(app);
return app;
}
//---------------------------------------------------------------------------
function doPost(e)
{
var app = UiApp.getActiveApplication();
try {
// 2nd step form
var fileBlob = e.parameter.thefile;
createRevisionForm();
}
catch(error) {
try {
// 3rd step form
createConfirmForm(e);
}
catch(error2) {
//Complete
sendMail(e);
modifySitePageContent(e);
saveHistoryFile(e);
showConfirmedInfo(e);
}
}
return app;
}
This answer is copied entirely from create a new page in a form dynamically, based on data of the prev. page.
Using the UiApp service, you have one doGet() and one doPost() function... but here's a way to extend them to support a dynamic multi-part form. (The example code is borrowed from this answer.)
Your doGet() simply builds part1 of your form. In the form, however, you need to identify your form by name, like this:
var form = app.createFormPanel().setId("emailCopyForm");
You doPost() then, will pass off handling of the post operation to different functions, depending on which form has been submitted. See below. (Also included: reportFormParameters (), a default handler that will display all data collected by a form part.)
/**
* doPost function with multi-form handling. Individual form handlers must
* return UiApp instances.
*/
function doPost(eventInfo) {
var app;
Logger.log("Form ID = %s", eventInfo.parameter.formId);
// Call appropriate handler for the posted form
switch (eventInfo.parameter.formId) {
case 'emailCopyForm':
app = postEmailCopyForm(eventInfo);
break;
default:
app = reportFormParameters (eventInfo);
break;
}
return app;
}
/**
* Debug function - returns a UiInstance containing all parameters from the
* provided form Event.
*
* Example of use:
* <pre>
* function doPost(eventInfo) {
* return reportFormParameters(eventInfo);
* }
* </pre>
*
* #param {Event} eventInfo Event from UiApp Form submission
*
* #return {UiInstance}
*/
function reportFormParameters (eventInfo) {
var app = UiApp.getActiveApplication();
var panel = app.createVerticalPanel();
panel.add(app.createLabel("Form submitted"));
for (var param in eventInfo.parameter) {
switch (param) {
// Skip the noise; these keys are used internally by UiApp
case 'lib':
case 'appId':
case 'formId':
case 'token':
case 'csid':
case 'mid':
break;
// Report parameters named in form
default:
panel.add(app.createLabel(" - " + param + " = " + eventInfo.parameter[param]));
break;
}
}
app.add(panel);
return app;
}
To generate each form part, subsequent form handlers can use the data retrieved in previous parts to dynamically add new Form objects to the ui.
I think it would be simpler to use 3 (or more) different panels in your doGet function with all the items you need and to play with their visibility.
At first only the 1rst panel would be visible and, depending on user input (using client Handlers to handle that) show the next ones (and eventually hide the first one).
In the end the submit button will call the doPost and get all data from the doGet.
First a tip of my hat to Mogsdad. His post(s) were guiding lights in the darkly documented path that led me here. Here is some working code
that demonstrates a multiple page form, i.e. it does the initial doGet() and then lets you advance back and forth doing multiple doPost()'s. All this is done in a single getForm() function called by both the standard doGet() and the doPost() functions.
// Muliple page form using Google Apps Script
function doGet(eventInfo) {return GUI(eventInfo)};
function doPost(eventInfo) {return GUI(eventInfo)};
function GUI (eventInfo) {
var n = (eventInfo.parameter.state == void(0) ? 0 : parseInt(eventInfo.parameter.state));
var ui = ((n == 0)? UiApp.createApplication() : UiApp.getActiveApplication());
var Form;
switch(n){
case 0: {
Form = getForm(eventInfo,n); // Use identical forms for demo purpose only
} break;
case 1: {
Form = getForm(eventInfo,n); // In reality, each form would differ but...
} break;
default: {
Form = getForm(eventInfo,n) // each form must abide by (implement) the hidden state variable
} break;
}
return ui.add(Form);
};
function getForm(eventInfo,n) {
var ui = UiApp.getActiveApplication();
// Increment the ID stored in a hidden text-box
var state = ui.createTextBox().setId('state').setName('state').setValue(1+n).setVisible(true).setEnabled(false);
var H1 = ui.createHTML("<H1>Form "+n+"</H1>");
var H2 = ui.createHTML(
"<h2>"+(eventInfo.parameter.formId==void(0)?"":"Created by submission of form "+eventInfo.parameter.formId)+"</h2>");
// Add three submit buttons to go forward, backward and to validate the form
var Next = ui.createSubmitButton("Next").setEnabled(true).setVisible(true);
var Back = ui.createSubmitButton("Back").setEnabled(n>1).setVisible(true);
var Validate = ui.createSubmitButton("Validate").setEnabled(n>0).setVisible(true);
var Buttons = ui.createHorizontalPanel().add(Back).add(Validate).add(Next);
var Body = ui.createVerticalPanel().add(H1).add(H2).add(state).add(Buttons).add(getParameters(eventInfo));
var Form = ui.createFormPanel().setId((n>0?'doPost[':'doGet[')+n+']').add(Body);
// Add client handlers using setText() to adjust state prior to form submission
// NB: Use of the .setValue(val) and .setValue(val,bool) methods give runtime errors!
var onClickValidateHandler = ui.createClientHandler().forTargets(state).setText(''+(parseInt(n)));
var onClickBackHandler = ui.createClientHandler().forTargets(state).setText(''+(parseInt(n)-1));
Validate.addClickHandler(onClickValidateHandler);
Back.addClickHandler(onClickBackHandler);
// Add a client handler executed prior to form submission
var onFormSubmit = ui.createClientHandler()
.forTargets(state).setEnabled(true) // Enable so value gets included in post parameters
.forTargets(Body).setStyleAttribute("backgroundColor","#EEE");
Form.addSubmitHandler(onFormSubmit);
return Form;
}
function getParameters(eventInfo) {
var ui = UiApp.getActiveApplication();
var panel = ui.createVerticalPanel().add(ui.createLabel("Parameters: "));
for( p in eventInfo.parameter)
panel.add(ui.createLabel(" - " + p + " = " + eventInfo.parameter[p]));
return panel;
}
The code uses a single "hidden" state (here visualized in a TextBox) and multiple SubmitButton's to allow the user to advance forward and backward through the form sequence, as well as to validate the contents of the form. The two extra SubmitButton's are "rewired" using ClientHandler's that simply modify the hidden state prior to form submission.
Notes
Note the use of the .setText(value) method in the client handler's. Using the Chrome browser I get weird runtime errors if I switch to either of the TextBox's .setValue(value) or .setValue(value, fireEvents) methods.
I tried (unsuccessfully) to implement this logic using a Script Property instead of the hidden TextBox. Instead of client handlers, this requires using server handlers. The behavior is erratic, suggesting to me that the asynchronous server-side events are occurring after the form submission event.

Nullpointer exception in Soundcloud HTML5 Widget API when creating dynamically new player iFrames

I could reduce my problem on a small code snippet. The code creates dynamically an SC player iFrame and displays the ready status. If there is already an iFrame, it removes the old one and creates a new one (runable example on JSFIDDLE):
var player;
var playerId;
var iframe;
var printReady=
function(data)
{
document.getElementById("status").innerHTML = "Ready";
};
function createSoundCloudIframe()
{
document.getElementById("status").innerHTML = "Player not ready";
var contentDiv = document.getElementById("content");
// Remove last Iframe
if(iframe != null){
player.unbind(SC.Widget.Events.READY);
contentDiv.removeChild(iframe);
}
// Create a new Iframe
iframe = document.createElement("IFRAME");
iframe.id = playerId + "ScId";
iframe.src = "http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F41867062&show_artwork=true";
// Append Iframe
contentDiv.appendChild(iframe);
// Show ready status
player = SC.Widget(playerId + "ScId");
player.bind(SC.Widget.Events.READY, printReady);
playerId ++;
};
The code runs fine when it is executed the first time. But when you try it a second time a nullpointer exception (developer console) will be thrown in this method of api.js:
// Uncaught TypeError: Cannot read property 'parentWindow' of null
function s(a) {
return a.contentWindow || a.contentDocument.parentWindow
}
The method which causes the exeption is SC.Widget(iFrameId);
This problem is in my case not solvable with SC.Widget(iFrameId).load(url, options); function and a hiding of the iFrame:
I wrote a google-web-toolkit wrapper for the SC widget api and use this wrapper with other gwt mediaplayer wrappers in a much bigger project. In this project the exception is thrown repeatedly with a delay of milliseconds which slows down everything. The codesnippet above is only a pure javascript reduction of the problem.
I really need a workaround which removes and clean up all dead references in the api.js when the iFrame is removed! I'm looking for such a workaround for month.

chrome indexed database setVersion request filled with exceptions

I am trying to get the following code to work on chrom by using setVersion (as onupgradeneeded is not available yet).
The IDBVersionChangeRequest is filled with IDBDatabaseException. And the onsuccess function could not be called. I need to create an ObjectStore within the onsuccess function.
specifically this line: request = browserDatabase._db.setVersion(browserDatabase._dbVersion.toString());
Below is my code. Any help would be greatly appreciated...
browserDatabase._db = null;
browserDatabase._dbVersion = 4;
browserDatabase._dbName = "mediaStorageDB";
browserDatabase._storeName = "myStore";
var request = indexedDB.open(browserDatabase._dbName);
// database exist
request.onsuccess = function(e)
{
browserDatabase._db = e.target.result;
// this is specifically for chrome, because it does not support onupgradeneeded
if (browserDatabase._dbVersion != browserDatabase._db.version)
{
request = browserDatabase._db.setVersion(browserDatabase._dbVersion.toString());
request.onerror = function(e) { alert("error") };
request.onblocked = function(e)
{
b = 11; // for some reason the code goes here...
}
request.onsuccess = function(e)
{
browserDatabase._db.createObjectStore(browserDatabase._storeName, {autoIncrement: true});
}
}
}
In your code sample you say you come in to the onblocked callback. The only way you can get in this callback is when you have still open transactions/connections to your db. (aside the one you are working in.) This means you will have to close all other transactions/connections before you can call the setVersion.
When wired things happen to IndexedDB, I "Clear data from hosted apps", quit Chrome windows and take a cup of coffee. After that everything work fine. :-D
browserDatabase._dbVersion < browserDatabase._db.version. Downgrading is not possible. dbVersion = 4 should not be consider lightly. You might open other tab with dbVersion = 5, or browser may be waining your response elsewhere or itself updating. All these are not worth to trace the reasons behind.

Execution order of GS files in a Project

Where can I read documentation concerning the execution order rules for GS files?
To dimension the problem I created two trivial objects, each in their own file.
1_File.gs
var ObjB = new Object();
ObjB.sayName = "[" + ObjA.sayName + "]";
0_File.gs
var ObjA = new Object();
ObjA.sayName = " I'm A ";
A call such as ...
Logger.log(ObjA.sayName + " : " + ObjB.sayName);
... gets the error ...
TypeError: Cannot read property "sayName" from undefined.
If I move the code from 1_File.gs into 0_File.gs, and vice versa, then there is no error and the log shows correctly ...
I'm A : [ I'm A ]
Renaming 0_File.gs to 2_File.gs doesn't affect execution order either, so I assume that order depends on which file gets created first.
Is there no concept of "include" or "import" that would allow me to make order of execution explicit?
Where can I read documentation concerning the execution order rules for GS files?
There is no such documentation and I think will not be any time published. In similar way, an initialization order of the static variables in C++ is also undefined and depends on compiler/linker.
Is there no concept of "include" or "import" that would allow me to make order of execution explicit?
Yes, there is no "includes", "imports" and even "modules", but there are libraries.
Also there is a workaround by using a closure. Bellow is a sample code. By executing the test function the log contains c.d. The idea is to have in all gs files a function started with init. In these functions all global variables are instanced. The anonymous closure is executed during the Code.gs file instancing and calls all "init" functions of all gs files.
Code.gs
var c;
function callAllInits_() {
var keys = Object.keys(this);
for (var i = 0; i < keys.length; i++) {
var funcName = keys[i];
if (funcName.indexOf("init") == 0) {
this[funcName].call(this);
}
}
}
(function() {
callAllInits_();
c = { value : 'c.' + d.value };
})();
function test() {
Logger.log(c.value);
}
d.gs
var d;
function initD() {
d = { value : 'd' };
};
I tackled this problem by creating a class in each file and making sure that each class is instantiated in the original Code.gs (which I renamed to _init.gs). Instantiating each class acts as a form of include and makes sure everything is in place before executing anything.
_init.gs:
// These instances can now be referred to in all other files
var Abc = new _Abc();
var Menu = new _Menu();
var Xyz = new _Xyz();
var Etc = new _Etc();
// We need the global context (this) in order to dynamically add functions to it
Menu.createGlobalFunctions(this);
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
Menu.build();
}
And classes usually look like this:
menu.gs:
function _Menu() {
this.build = function() {
...
}
...
}
If you have more than one level of inheritance, you need to give the init functions names like init000Foo, init010Bar, and init020Baz, and then sort the init functions by name before executing. This will ensure init000Foo gets evaluated first, then Bar, then Baz.
function callAllInits() {
var keys = Object.keys(this);
var inits = new Array();
for (var i = 0; i < keys.length; i += 1) {
var funcName = keys[i];
if (funcName.indexOf("init") == 0) {
inits.push(funcName);
}
}
inits.sort();
for (var i = 0; i < inits.length; i += 1) {
// To see init order:
// Logger.log("Initializing " + inits[i]);
this[inits[i]].call(this);
}
}
The other answers (i.e., don't write any top-level code which references objects in other files) describe the ideal way to avoid this problem. However, if you've already written a lot of code and rewriting it is not feasible, there is a workaround:
Google App Script appears to load code files in the order they were created. The oldest file first, followed by the next, and the most recently created file last. This is the order displayed in the editor when "Sort files alphabetically" is unchecked.
Thus, if you have the files in this order:
Code.gs
1_File.gs (depends on 0_File.gs)
0_File.gs
An easy fix is to make a copy of 1_File.gs and then delete the original, effectively moving it to the end of the list.
Click the triangle next to 1_File.gs and select "Make a copy"
Code.gs
1_File.gs
0_File.gs
1_File copy.gs
Click the triangle next to 1_File.gs and select "Delete"
Code.gs
0_File.gs
1_File copy.gs
Click the triangle next to 1_File copy.gs and select "Rename", then remove the " copy" from the end.
Code.gs
0_File.gs
1_File.gs
Now 0_File.gs is loaded before 1_File.gs.
This works for me as of December 2021. Quite likely, the other answers are outdated.
You can easily fix this. When you look at the scripts in the "Files" section of the web editor, you see they have an order. Files are evaluated in the order they appear there. Clicking on the three dots to the right of a file name brings up a menu that allows you to move a file up or down.
There is no such order in Google Apps Script. It purely depends on where you have these objects declared and how your function is invoked.
Can you explain a bit about how and when your Logger.log() code will be invoked.
Also, when do you declare your objects objA and objB ?
These will help us provide a better answer
here is how I would do this...
main
function include(filename) {
return ContentService.createTextOutput(filename);
}
function main() {
include('Obj A');
include('Obj B');
Logger.log(ObjA.sayName + " : " + ObjB.sayName);
}
Obj A
var ObjA = new Object();
ObjA.sayName = " I'm A ";
Obj B
var ObjB = new Object();
ObjB.sayName = "[" + ObjA.sayName + "]";