Cordova SQLite plugin only works on first call - javascript

I have a cordova app with two pages, the first has a search field and the second displays the results of the first.
The displayResults function
function displayResults(){
var query = localStorage.getItem('search');
var db = window.sqlitePlugin.openDatabase({name:"Store-DB", location: 1});
queryDB(db,query);
}
function queryDB(db,query){
db.transaction(function(tx) {
var queryList = query.split(" ");
var sqlText = "SELECT * FROM DB WHERE item LIKE '%"+queryList[0]+"%'";
for (i = 1; i < queryList.length; i++) {
sqlText += " OR item LIKE '%"+queryList[i]+"%'";
}
tx.executeSql(sqlText, [], querySuccess);
}
);
}
function querySuccess(tx,results) {
var i;
var len = results.rows.length;
//Iterate through the results
for (i = 0; i < len; i++) {
console.log(row);
//Get the current row
var row = results.rows.item(i);
var div = document.createElement("div");
div.style.background = "gray";
div.style.color = "white";
div.innerHTML = row;
document.body.appendChild(div);
}
alert("Finished");
}
Here is the code for the second page:
<link rel="stylesheet" type="text/css" href="css/default.css">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/zepto.js" type="text/javascript"></script>
<script src="plugins/com.brodysoft.sqlitePlugin/www/SQLitePlugin.js" type="text/javascript"></script>
<script src="js/code.js" type="text/javascript"></script>
<script type="text/javascript">
function onLoad(){
document.addEventListener("deviceready", onDeviceReady(), false);
}
function onDeviceReady(){
displayResults();
}
</script>
</head>
<body onload="onLoad()">
<div id="taskbar">
Home
<a id="username" class="toolbar_item" style="float:right;" href="#"></a>
</div>
The first time you load this page displayResults works just fine, but if you click the link back to the main page and load the second page again the console prints the error ReferenceError: no "undefined" has no property "openDatabase" in other words, the SQLite plugin isn't loading. But, if I make displayResults fire on a button press instead of onload it works every time. What is the explanation for this peculiar behavior?

It seems that sometimes deviceready-event is either not fired at all or fired too early when there are more event handlers of different libraries in place. The second problem caused that the brodysoft-plugin is not loaded properly and assign to the window-object as window.sqlitePlugin property because one event handler dispatched deviceready-event too early. It turned out setTimeout was the answer as it had been here

You can use the onpageshow event for example
$('#idofyourpage').bind("onpageshow",function(){
//Do something
});

Related

show Dialogue while function runs

I'm loading thumbnails before image upload starts with
window.URL = window.URL || window.webkitURL;
function fileThumbnail(files)
{
var thumb = document.getElementById("thumbnail");
// thumb.innerHTML = "";
if(!files)
return;
for (var i = 0; i < files.length; i++)
{
var file = files[i];
if(!file.type.match(/image.*/))
continue;
var img = document.createElement("img");
img.src = window.URL.createObjectURL(file);
img.width = 100;
img.onload = function(e) {
window.URL.revokeObjectURL(this.src);
};
thumb.appendChild(img);
}
}
which can last for a long time if many pictures selected.
I would like to show a dialogue or even a dialogue with progress bar while the thubnails are created.
can you please tell me how to do that?
and besideds that, if I use this script twice: are the pictures selected on the second run appended to the array "files" or are the replaced? please tell me how to append them so that you can choose pictures several times before you press an upload button.
thank you very much for your help!
i would recommend having a separate function toggling the display of the loading dialog, and calling it at the beginning and end of your function that is time consuming.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div id="progressbar" ></div>
</body>
<script>
var process=0;
function transition()
{
process+=5;
$( "#progressbar" ).progressbar({
value: process
});
if(process==100)
process=0;
}
setInterval(transition, 200);
</script>
</html>

Execute javascript after page load is complete [duplicate]

This question already has answers here:
How to make JavaScript execute after page load?
(25 answers)
Closed 2 years ago.
I have an html page with some pre-rendered content and some yet un-rendered content. I want to display the pre-rendered content immediately, and then begin rendering the rest of the content. I am not using jQuery.
See the following snippet. I have tried this various ways, including injecting my script before the closing body tag and providing my script to populate the DOM as a callback to window.onload, document.body.onload, and document.addEventListener('DOMContentLoaded'). In every case, the page does not display the pre-rendered content until the rest of the content is rendered.
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
for (var i = 0; i < 500; i++)
main.innerText += new Date();
</script>
</body>
</html>
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
document.body.onload = function() {
for (var i = 0; i < 500; i++)
main.innerText += new Date();
};
</script>
</body>
</html>
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
window.onload = function() {
for (var i = 0; i < 500; i++)
main.innerText += new Date();
};
</script>
</body>
</html>
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
document.addEventListener('DOMContentLoaded', function() {
for (var i = 0; i < 500; i++)
main.innerText += new Date();
});
</script>
</body>
</html>
One case that has worked is window.setTimeout with 0 timeout. However, this simply defers the function until there is nothing left to do. Is this the best practice, here?
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
window.setTimeout(function() {
for (var i = 0; i < 500; i++)
main.innerText += new Date();
}, 0);
</script>
</body>
</html>
In terms of a best practice, there isn't one. In terms of a good, common, and acceptable practices, there are a handful. You've hit one:
setTimeout(function() { }, 1);
In this case, the function is executed within the browser's minimum timeout period after all other in-line processing ends.
Similarly, if you want to ensure your function runs shortly after some condition is true, use an interval:
var readyCheck = setInterval(function() {
if (readyCondition) {
/* do stuff */
clearInterval(readyCheck);
}
}, 1);
I've been using a similar, but more generalized solution in my own work. I define a helper function in the header:
var upon = function(test, fn) {
if (typeof(test) == 'function' && test()) {
fn();
} else if (typeof(test) == 'string' && window[test]) {
fn();
} else {
setTimeout(function() { upon(test, fn); }, 50);
}
}; // upon()
... and I trigger other functionality when dependencies are resolved:
upon(function() { return MyNS.Thingy; }, function() {
// stuff that depends on MyNS.Thingy
});
upon(function() { return document.readyState == 'complete';}, function() {
// stuff that depends on a fully rendered document
});
Or, if you want a more authoritative good practice, follow Google's example. Create an external async script and inject it before your first header script:
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true;
s.src = '/path/to/script.js';
var header_scripts = document.getElementsByTagName('script')[0];
header_scripts.parentNode.insertBefore(s, header_scripts);
Google's solution theoretically works on all browsers (IE < 10?) to get an external script executing as soon as possible without interfering with document loading.
If you want an authoritative common practice, check the source for jQuery's onready solution.
Depending on your browser requirements you can use the async tag and import your script after content loads. This probably accomplishes the same thing as setTimeout(func, 0), but perhaps it's a little less hacky.
See http://plnkr.co/edit/7DlNWNHnyX5s6UE8AFiU?p=preview
html:
...
<body>
<h1 id="main">Hello Plunker!</h1>
<script async src="script.js"></script>
</body>
...
script.js:
for(var i=0; i<500; ++i) {
document.getElementById('main').innerText += new Date();
}
I've used this to effect before:
var everythingLoaded = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(everythingLoaded);
init(); // this is the function that gets called when everything is loaded
}
}, 10);
I think what you want to do is use an onload event on the tag.
This way first the "What it is, my doge?" message will appear while the javascript is processed.
I also set a timeout inside the loop, so you can see better the lines being added.
<html>
<head>
<script>
myFunction = function() {
for (var i = 1000; i > 0; i--) {
setTimeout(function() {
main.innerText += new Date();
}, 100);
}
};
</script>
</head>
<body onload="myFunction()">
<header>What it is, my doge?</header>
<div id="main"></div>
</body>
</html>

execute google image search several times in a page

I want to write a web page which can generate images get from google search dynamically.
The search terms for these images are different, so I need to execute google search several times, while I found it is very hard.
I try these code modified from the source code google provided, but it could only execute the search one time:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Search API Sample</title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
var imageSearch;
var keyword="sexy";
function searchComplete() {
// Check that we got results
if (imageSearch.results && imageSearch.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
var results = imageSearch.results;
for (var i = 0; i < results.length; i++) {
// For each result image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src=result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
//clear search
imageSearch.clearResults();
}
}
function OnLoad() {
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// Set searchComplete as the callback function when a search is
// complete. The imageSearch object will have results in it.
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
imageSearch.execute(keyword);
}
function hi(){
keyword="usa";
alert('hi');
google.setOnLoadCallback(OnLoad);
imageSearch.execute(keyword);
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<button value="hi" onClick="hi">hi</button>
<div id="content">Loading...</div>
</body>
</html>
The program can only execute the search in OnLoad method. Actually, I tried to call google.setOnLoadCallback(OnLoad) multiple times by put it into hi() function, but it didn't work.
Hope someone can help me to solve these problem..
change <button value="hi" onClick="hi">hi</button> to
<button value="hi" onClick="hi()">hi</button>
The hi function doesn't make a lot of sense to me:
function hi(){
keyword="usa";
alert('hi');
google.setOnLoadCallback(OnLoad);
imageSearch.execute(keyword);
}
Because the onLoadCallbak has already been set, and a search executed in OnLoad. This is called when the search library has loaded. Which only happens once, at some point after the page has loaded.
What you need to do in hi is the same thing you're doing in OnLoad:
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// set a DIFFERENT callback (if different handling require)
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
// set "keyword" to what your next search should be for
imageSearch.execute(keyword);

Simple Javascript Gallery

So I'm trying to loop through this array and change an image source every few seconds. Right now I have an onload event calling a setTimeOut method which should change the image 5 seconds after the page has loaded I would think, but it is doing it instantly. What is the problem? Here is my code:
<html>
<head>
<title>Ad Rotaror</title>
<script type="text/javascript">
var i = 0;
var ads = new Array(4);
ads[0]='promo1.gif';
ads[1]='promo2.gif';
ads[2]='promo3.gif';
ads[3]='promo4.gif';
ads[4]='promo5.gif';
function change()
{
if(i > 4)
i = 0;
document.images[0].src = ads[i];
i++;
}
</script>
</head>
<body>
<img src="promo1.gif" onload="setInterval(change(), 5000)" />
</body>
</html>
Change 'change()' to 'change'. You are calling the function immediately.

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources