LocalStorage in Phonegap across different pages - javascript

I'm trying to use a simple string stored in the localStorage functionality built into phonegap as a simple setting to deicide witch set of data to fetch from a server. In the index.html I've been able to save a string from a <select> menu and display it in the header. Using this javascript code:
<script type="text/javascript" charset="utf-8">
window.onload = function() {
document.getElementById("BtnStore").addEventListener("click", storeData, false);
$("#headertitle").append(loadData()).headertitle("refresh");
}
function storeData() {
var e = document.getElementById("klass");
var klass = e.options[e.selectedIndex].value;
localStorage.setItem("klass", klass);
window.location.href = "index.html";
}
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
This appends the stored value in an <h1> element.
But when I from a different html page try to reference the same key from the localstore, nothing is being displayed. Here is that code:
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$("#hejsan").append(loadData()).hejsan("refresh");
};
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
This is also just as a test, appending the string to a <p> element. For some reason nothing is happening, someone knows why?
Thanks

I figured out how to make it work, here is the code i used:
First page:
<script type="text/javascript" charset="utf-8">
window.onload = function() {
document.getElementById("BtnStore").addEventListener("click", storeData, false);
$("#headertitle").html(loadData()).headertitle;
}
function storeData() {
//localStorage.clear();
var e = document.getElementById("klass");
var klass = e.options[e.selectedIndex].value;
localStorage.setItem("klass", klass);
window.location.href = "index.html";
}
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
Second page:
$(document).ready(function() {
function loadData() {
var getKlass = localStorage.getItem("klass");
$("#hejsan").html(getKlass).hejsan;
}
loadData();
}
If anyone else gets stuck! :)

Related

How to access data from other homepage with a simple function (no Ajax, no jQuery)

I want to access the data returned by this link with a simple function: https://geoapi123.appspot.com/
If you click the link, the return looks like:
function geoip_country_code(){return"UK"}
function geoip_country_name(){return"United Kingdom"}
function geoip_city(){return"London"}
...
In particular, I'm looking for the geoip_city. I do not want to use AJAX or jQuery.
I need a simple function, which does nor require script tags or any references in the head. The data received needs to be stored in a variable, totally independent from the homepage or any events at the homepage. The function cannot be called by any onload or click events, or anything else happening with the homepage.
Here is a working example with head script tag (not what I want):
<head>
<script language="JavaScript" src="https://geoapi123.appspot.com/"></script>
</head>
<body>
<script language="JavaScript">
var city = geoip_city();
alert(city);
</script>
</body>
Here is an idea of what I want:
function getLocation() {
??? //access homepage somehow here
var city = geoip_city(); //get result
alert(city); //alert result
};
getLocation(); //call function
Here is my closest try so far (not working, the return is "0"):
function accessLocation() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", "https://geoapi123.appspot.com", true);
xmlhttp.send();
};
accessLocation();
You can add a script element by code and loading the source from 'geoapi':
function clickHandler() {
var city = geoip_city();
alert(city);
}
function ready() {
var element = document.getElementById('cityFinder');
element.addEventListener('click', clickHandler, false);
}
function init() {
var script = document.createElement('script');
script.onload = function() {
ready();
};
script.src = "https://geoapi123.appspot.com/";
document.getElementsByTagName('head')[0].appendChild(script);
}
<body onload="init();">
<input type="button" id="cityFinder" value="Where am I?"></input>
</body>

Mvc complete asynchronous scripts loading

I have a small problem with asynchronous loading scripts on my web page.
I need to load all scripts of page asynchronously. I tried many procedures, which I found on google, but still it is not perfect.
Now I have it like this:
Split all scripts from layout to one bundle including jquery.
On bottom of the page call RenderFormat with async tag.
Now this is where I get the problem: I need to solve the situation where
the scripts are being rendered by #RenderFormat. The problem is that those
scripts are being rendered earlier than I need.
For example I have this in Home/Index file:
#Scripts.RenderFormat("<script async type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/raphael")
or simply
...
$(".datapicker").datapicker();
...
Here we get error, "$ is not defined", because jquery is not loaded yet.
After content, in Layout file I have:
...
#Scripts.RenderFormat("<script async type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/frontall")
...
#RenderSection("scripts", required: false)
If I take all of my scripts on page and give them to one bundle, everything is fine, but I don't want scripts to get rendered,
I need to do that only in a specific section.
Next idea was to create a custom RenderSection method, that will do someting like this:
function async(u, c) {
var d = document, t = 'script',
o = d.createElement(t),
s = d.getElementsByTagName(t)[0];
o.src = u;
if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
s.parentNode.appendChild(o, s);
}
async("/bundles/jquery", function() {
//here, load scripts from inner pages. Index, Detail...
});
Is there way, how to solve it?
Thank you very much for your time.
Ok guys, solved.
There is my current scrips in layout:
...
#RenderSection("scripts", required: false)
<script>
function async(u, c, css) {
var t = 'script';
var element = document.createElement(t);
var s = document.getElementsByTagName(t)[0];
element.src = u;
if (css) {
t = "link";
element = document.createElement(t);
element.href = u;
element.rel = 'stylesheet';
element.src = null;
var head = document.getElementsByTagName('head')[0];
head.appendChild(element, head);
return;
}
if (c) { element.addEventListener('load', function (e) { c(null, e); }, false); }
s.parentNode.appendChild(element, s);
}
function initScripts() {
async("/content/css", null, true);
async("/bundles/jquery", function () {
#RenderSection("asyncScripts", required: false)
});
}
if (window.addEventListener) {
window.addEventListener("load", function () {
initScripts();
}, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", function () {
initScripts();
});
} else {
window.onload = function () {
initScripts();
};
}
</script>
And in other files. (Index, Detail...)
#section scripts {
<script type="text/javascript">
var czech_republic = {};
window.selectedRegions = [];
czech_republic.regions = {
#Html.Raw(string.Join(", ", regions.Select(r => string.Format("\"{0}\": \"{1}\"", r.RaphaelId, r.RaphaelCoordinates))))
};
</script>
#section asyncScripts {
#Scripts.RenderFormat("async(\"{0}\");", "~/bundles/raphael");
}
If you need call next scripts, for example after raphael, you simple create new callback in renderformat async a that's all.
Thanks to all

onclick event not firing based on boolean flag

I'm working on some code where if a user clicks on a particular button, that person is NOT presented with an exit popup upon exiting the page. The way I'm doing it is by setting a flag whenever the user clicks on the button. However, my code isn't working as expected: The popup loads whether or not the button is clicked. I don't understand why.
Edit: Help!
<!doctype html>
<html>
<head>
<title>Test!</title>
<script>
var bool = false;
var config = new Object();
config.surveyID = 3155031;
config.takeSurveyURL = 'http://www.supporterfeedback.org/a/TakeSurvey';
config.windowPositionLeft = 200;
config.windowPositionTop = 300;
config.home = 'http://www.surveyanalytics.com/';
config.isRightToLeft = false;
config.showFooter = true;
// document.getElementById("btn").onclick = function()
// {
// bool = true;
// };
function flag() {
bool = true;
}
if (!bool) {
window.onbeforeunload = function () {
QP_popupMain();
};
}
</script>
<script language="javascript"
src="http://www.surveyanalytics.com//javascript/exitSurveyInvitation.js"
type="text/javascript"></script>
<noscript>
Start Survey
</noscript>
</head>
<body>
<a href="http://google.com"><img id="btn" onclick="flag()"
src="http://kelowna.directrouter.com/~jeasprco/wp-content/uploads/2012/05/PanicButton2.png"/></a>
<p>Hello, this is a test!</p>
</body>
</html>
I think window.onbeforeunload = function () is operating as soon as the page loads, so what is inside if(!bool) is executing on the button press.
Try changing these two lines:
// var bool = false;
var bool;
// if (!bool) {
if (bool == false) {
You're testing the flag once, when you assign the .beforeunload handler when the page is loaded. Calling flag() doesn't re-execute that code. You need to test it when the function is called.
window.onbeforeunload = function() {
if (!bool) {
return "You haven't clicked the button, do you really want to leave?"
}
}

How javascript detects where the function is defined, top/bottom?

I have the below code is working as long as I load the employee section and its scripts as part of the index.html
index.html Working Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Employee Details loaded as usual and sript is executing able to see alert</h1>
</body>
</html>
Script.js
var empModule = (function (empModule) {
var Years = null;
$(document).ready(function () {
var empdata = { Name: 'Billa' }
var myVM = new empModule.viewModel(empdata);
});
empModule.viewModel = function (data) {
var that = this;
that.Name = data.Name;
alert(that.Name);
};
return {
empModule: empModule
}
} (empModule || {}));
Error Scenario:
We decide to move employee related section based on some condition. Hence we are loading this section and section related script(emp.js) via Ajax. But now it is throwing the error empModule.viewModel is not a constructor. Why is it so?
If I move the document.ready section at the bottom like the below order, it is working
Emp.js(moved from script.js to emp.js and load via ajax(
var empModule = (function (empModule) {
var Years = null;
// Code not working when we load this script file using Ajax.
// But works if we move this document.ready at bottom
//$(document).ready(function () {
// var empdata = { Name: 'Billa' }
// var myVM = new empModule.viewModel(empdata);
//});
empModule.viewModel = function (data) {
var that = this;
that.Name = data.Name;
alert(that.Name);
};
//Working only if I keep the ready section here
$(document).ready(function () {
var empdata = { Name: 'Billa' }
var myVM = new empModule.viewModel(empdata);
});
return {
empModule: empModule
}
} (empModule || {}));
The function empModule will get executed automatically as it is self
executing function. When it is executing it needs to prepare a
empModule.viewModel object, but failed to do that when viewModel
definition is located after document.ready (caller). This happens only
when I load this script via Ajax, but works if I pre load it in a page
This is because in the first example the script.js is part of the document and therefore the document.ready waits for that .js file to be loaded before trying to call empModule.viewModel().
In the second example, your script is loaded asyncronously, but the page is not taking this into account. So the page loads (without the script.js) and then you load the script.
At this point, the document is ready (as the ajax loaded script isn't part of the document) so the empModule.viewModel() call fires straight away, before the rest of the script (which is the bit that defines the function) and you get your error.
Just like #dougajmcdonald said is your issue, but your solution is, instead of loadding by AJAX, just insert the script tag in your document:
// Instead of $.ajax(... /myScript.js) use:
function loadMyScript(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'myScript.js';
script.onload = function() {
empModule.doSomething(); // or callback
};
}

Why won't this web page finish loading?

If I run this code, why doesn't the page ever finish loading? It will always show connecting on my browser tab.
It is a simple javascript which will prompt an alert box and change the entire document to the word testing.
Javascript - testQuery.js
(function (window, undefined) {
var testQuery = function(obj) {
if (!(this instanceof testQuery)) {
return new testQuery(obj);
}
}
testQuery.alertMessage = function () {
alert("alert");
document.write("testing");
};
window.testQuery = testQuery;
}) (window);
HTML - testQuery.html
<html>
<head>
<script src="testQuery.js"></script>
<script>
function onClick() {
testQuery.alertMessage();
}
</script>
</head>
Because you didn't close the document.
document.close()

Categories

Resources