CordovaFileTransfer | How put string from the headers to TargetPath? - javascript

I have project write with Ionic Framework and AngularJS.
His task is to download files from the URL, type as http://www.uzhnu.edu.ua/uk/infocentre/get/6500
The problem is that the examples of "how to download the file and give it a name" is only if the path to URL line have his name .
The name of my file does not have this name in url. It is in the headers of http request, here is screen made with POSTMAN, but how to get it and put in a variable TargetPath, I do not know. Can anyone suggest something?
Here is code of
FileTransferController.js:
app.controller('MyCtrl', function($scope, $cordovaFile, $cordovaDialogs, $window, $ionicLoading,$ionicPopup, $timeout, $cordovaFileTransfer) {
$scope.id = '6500';
$scope.downloadFile = function() {
$ionicLoading.show({template: 'Download file...'});
var url = "http://www.uzhnu.edu.ua/uk/infocentre/get/"+$scope.id;
var filename = $scope.id+".doc";
alert(filename);
var targetPath = "/storage/sdcard0/documents/" + filename;
var trustHosts = true;
var options = {};
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(entry) {
// Success!
$ionicLoading.hide();
console.log('download complete: ' + entry.toURL());
alert('File download: ' + targetPath);
}, function(error) {
$ionicLoading.hide();
// An error occured. Show a message to the user
alert('Sorry');
alert(JSON.stringify(error));
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
"Content-Disposition": ""
},
});
};
});
app.js:
var app = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- ng-cordova -->
<script src="js/ng-cordova.js"></script>
<script src="js/ng-cordova.js"></script>
<script src="js/ng-cordova.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/FileTransferController.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content ng-controller="MyCtrl">
<button class="button-positive" ng-click="downloadFile()">Download File</button>
</ion-content>
</ion-pane>
</body>
</html>
P.S. Code work only on real device. And must download all plugins:
ionic plugin add cordova-plugin-file
ionic plugin add cordova-plugin-file-transfer
and in folder "js" add file "ng-cordova.js" and "ng-cordova.min.js". DOwnload they can with:
bower install ngCordova

YES! Finally I did it!If someone will need a code, her ir is:
$scope.downloadFile = function() {
var url = "http://example.com/page";
$ionicLoading.show({template: 'Download file...'});
$http.get(url).
success(function (data, status, headers) {
var head = headers('Content-Disposition');
var filename = head.substr(head.lastIndexOf('=')+1);
alert(filename);
var targetPath = "/storage/sdcard0/documents/" + filename;
var trustHosts = true;
var options = {};
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(entry) {
$ionicLoading.hide();
console.log('download complete: ' + entry.toURL());
alert('File download: ' + targetPath);
}, function(error) {
$ionicLoading.hide();
console.log('headers: ' + headers('Cache-Control'));
// An error occured. Show a message to the user
alert('Sorry');
alert(JSON.stringify(error));
})
alert(head1);
$ionicLoading.hide();
$scope.$broadcast('scroll.refreshComplete');
return(JSON.stringify(head1))
})
.error(function (status) {
alert(status);
$ionicLoading.hide();
$scope.$broadcast('scroll.refreshComplete');
});
};

Related

Monaca is playing the same music even though I have two different music files

I have two play buttons in the html file configured with two different music. But both the play buttons are playing the same music. When I tried to print the media object before playing, they're printing different different objects.
Kindly assist me with the issue.
I have added Media plugin in Monaca for this code.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv="Content-Security-Policy" content="default-src * data: gap: https://ssl.gstatic.com; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
<link rel="stylesheet" href="components/loader.css">
<script src="components/loader.js"></script>
<script>
var media1 = null;
var media2 = null;
var srcFile2 = "https://download.samplelib.com/mp3/sample-9s.mp3";
var srcFile1 = "https://download.samplelib.com/mp3/sample-12s.mp3";
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("ready");
media1 = new Media(srcFile1, onSuccess, onError);
media2 = new Media(srcFile2, onSuccess, onError);
}
function playSound1() {
console.log(media1);
media1.play({
numberOfLoops: 0
});
}
function playSound2() {
console.log(media2);
media2.play({
numberOfLoops: 0
});
}
function pauseSound(src) {
console.log(src);
if (src == "1" && media1) {
media1.pause();
} else if (src == "2" && media2) {
media2.pause();
}
}
function stopSound(src) {
if (src == "1" && media1) {
media1.stop();
} else if (src == "2" && media2) {
media2.stop();
}
}
function onSuccess() {
console.log("Successfully initialize a media file.");
}
function onError(error) {
console.log("Failed to initialize a media file. [ Error code: " + error.code + ", Error message: " + error.message + "]");
}
</script>
</head>
<body>
<div>
<h3>Music 1</h3>
<button onclick="playSound1()">Play</button>
<button onclick="pauseSound(1)">Pause</button>
<button onclick="stopSound(1)">Stop</button><br />
<!-- <p id="audio_position"></p> -->
</div>
<div>
<h3>Music 2</h3>
<button onclick="playSound2()">Play</button>
<button onclick="pauseSound(2)">Pause</button>
<button onclick="stopSound(2)">Stop</button><br />
<!-- <p id="audio_position"></p> -->
</div>
</body>
</html>

How to use Cordova InAppBrowser into a HostedWebApps?

I have a website with 2 mobile-apps displayed with Cordova, and they works really great. But I have a problem :
When an external link is triggered by the user, he go out of the application and don't have any possibility to come back on the App... (except close and reopen).
I have installed inappbrowser according to this tutorial. Sounds very simple but not working...
Console :
cordova plugin add cordova-plugin-inappbrowser
Link (supposed to trigger InAppBrowser - not working) :
www.google.com
And I just remembered, that my apps are displayed with a technique named Hosted Web App. And maybe it's what InAppBrowser does not work : we are already in a webbrowser ?!
I will snip my config & js code bellow, here's the tutorial of Microsoft who helped me on the App setting.
Goal : find a way to use InAppBrowser, because we have a lot of external links in our website.
Any ideas please ?
Many thanks !
Here is the code :
Index.js
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
// Here, we redirect to the web site.
var targetUrl = "https://www.website.test/";
var bkpLink = document.getElementById("bkpLink");
bkpLink.setAttribute("href", targetUrl);
bkpLink.text = targetUrl;
window.location.replace(targetUrl);
},
// Note: This code is taken from the Cordova CLI template.
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
App.js
/*global app, $on */
(function () {
'use strict';
/**
* Sets up a brand new Todo list.
*
* #param {string} name The name of your new to do list.
*/
function Todo(name) {
this.storage = new app.Store(name);
this.model = new app.Model(this.storage);
this.template = new app.Template();
this.view = new app.View(this.template);
this.controller = new app.Controller(this.model, this.view);
}
var todo = new Todo('todos-vanillajs');
function setView() {
todo.controller.setView(document.location.hash);
}
$on(window, 'load', setView);
$on(window, 'hashchange', setView);
var onSuccess = function(position) {
var geotext = document.getElementById('geotext');
geotext.textContent = 'Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude;
};
var onError = function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var button = document.getElementById('geo');
button.addEventListener("click", function(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
});
function myOnDeviceReady() {
if (navigator.connection.type == Connection.NONE) {
navigator.notification.alert('An internet connection is required to continue');
} else {
window.location="https://www.website.test/";
}
}
document.addEventListener("deviceready", myOnDeviceReady, false);
})();
Index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="viewport-fit=cover, initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" />
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://www.website.test/ https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<title>mysite</title>
<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
<link rel="stylesheet" type="text/css" href="css/overrides.css" />
</head>
<a id="bkpLink" href="https://www.website.test/" class="mysite_font">mysite</a>
<div class="app">
<img src="img/logo_gradient.png" style="width: 200px;">
<div id="deviceready" class="blink">
<p class="mysite_font event listening">Chargement de l'app...</p>
<p class="mysite_font event received">Chargement...<br/>Merci de patienter quelques instants.</p>
</div>
</div>
<script type="text/javascript" src="scripts/index.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="node_modules/todomvc-common/base.js"></script>
<script src="js/helpers.js"></script>
<script src="js/store.js"></script>
<script src="js/model.js"></script>
<script src="js/template.js"></script>
<script src="js/view.js"></script>
<script src="js/controller.js"></script>
<script src="js/app.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</html>
From your question and follow ups, I'm assuming you are loading in yourwebsite.com into your mobile app, then on yourwebsite.com you want to open external links but keep otherwebsite.com within your app. If I'm understanding correctly, you can load yourwebsite.com in your mobile app and open external links with inAppBrowser by sending a postMessage() back to your mobile app with the external link.
First, loading in yourwebsite.com within an <iframe> on your mobile app:
<iframe src="https://www.yourwebsite.com">
On yourwebsite.com, when an external link is clicked (in my example, this anything with . external_url class and you'll most likely have to use querySelectorAll instead for multiple links), capture it with JS and send the href value back to the mobile app with postMessage():
document.querySelector('.external_url').addEventListener('click', function(event) {
event.preventDefault(); // stops the user from loading this link
var data = {'external_url': event.target.href};
window.parent.postMessage(data, '*');
});
Back on your mobile app, you need to listen to incoming postMesssage(). And trigger inAppBrowser to open the external url that was passed back from yourwebsite.com.
window.addEventListener('message', function(event) {
if (event.data.external_url) {
window.cordova.InAppBrowser.open(event.data.external_url, '_blank', 'location=no');
}
}, true);
I have not tested this code, but it should get you pointed in the right direction with a few changes.

Access-Control-Allow-Origin Error..(using cordova)

I'm trying to web server and client..(Hybrid app! using cordova)
But Access-Control-Allow-Origin error..so I downloaded chrome extension program cors.. but doesn't working..
[server.js]
var app = require('express')();
var http = require('http').Server(app);
var cors = require('cors');
var io = require('socket.io')(http);
// io.set('origins','*:*');
io.on('connection', function(socket){
console.log('a user connected');
socket.on('weather_location', function(msg){
socket.emit('message', msg);
})
});
http.listen(80, function(){
console.log('listening on *:3737');
});
[index.html]
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<html>
<head>
<title>location_weather</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- <script type='text/javascript' src='/socket.io/socket.io.js'></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.0/socket.io.slim.js"/>
<!-- <script type="text/javascript" src="./js/socket.io.js"/> -->
<script type="text/javascript" src="https://openapi.map.naver.com/openapi/v3/maps.js?clientId=irru1vaga0dOPnfgy29o&submodules=geocoder"></script>
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src ws://example.com wss://example.com"> -->
</head>
<body>
<button id="weatherBtn" onclick="weather_location();">클릭</button>
</body>
</html>
<script>
var socket = io.connect('http://202.31.200.138:80');
//var socket = io();ttp
$(function (){
//var socket = io.connect('http://202.31.200.138:3330');
socket.on('message', function(data){
console.log(data);
alert(data);
});
});
function weather_location(){
alert("hello");
socket.emit('weather_location','message');
}
// function location_weather(){
// if(navigator.geolocation){
// navigator.geolocation.getCurrentPosition(function(position){
// alert("위도 : " + position.coords.latitude + "tt" + position.coords.longitude);
// }, function(error){
// console.error(error);
// },{
// enableHighAccuracy : false,
// maximumAge : 0,
// timeout : Infinity
// });
// socket.emit('weather_location',position.coords.latitude );
// } else {
// alert("GPS를 지원하지 않습니다.");
// }
// //return false;
// }
</script>
[error]
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Please Help me...
You need to add the whitelist plugin,
https://github.com/apache/cordova-plugin-whitelist
In config.xml add
<!-- will not stop any calls -->
<access origin="*" />
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
You can use like this also , may be it will help.
This might be related to chrome issue if your cordova is using chrome as a default browser of webview. I've encounter the issue on v76.0.3809.89 of chrome and updating to v76.0.3809.111 solved the Access-Control-Allow-Origin issue.
Try using the cors in you app middleware
app.use(cors());

How to send form data with window.open() using InAppBrowser

I have a requirement that i need to send form data with window.open(). am going to integrate PayU money to Ionic and AngularJS application at that scenario i need to send some form data from window.ope() using InAppBrowser Cordova plugin but am not able to send form data.
following code written in my app.js
var example = angular.module('starter', ['ionic', 'ngSanitize']);
example.run(function($ionicPlatform, $timeout) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
});
example.controller("ExampleController", ['$scope', '$interval', function($scope, $interval) {
$scope.myHTML = 'Check out my programming blog while you are here';
$scope.testmethod = function() {
onDeviceReadyEWEWE();
}
}]);
// Global InAppBrowser reference
var iabRef = null;
function iabLoadStart(event) {
var winName = 'MyWindow';
//var winURL='https://test.payu.in/_payment.php';
var winURL = 'https://test.payu.in/_payment';
// var winURL='https://test.payu.in/merchant/postservice.php?form=2';
var windowoption = 'resizable=yes,height=600,width=800,location=0,menubar=0,scrollbars=1';
//var params = { 'param1' : '1','param2' :'2'};
var params = {
'key': 'gtKFFx',
'txnid': 'mdd0sss9023',
'amount': '100',
'productinfo': 'oxygenconcentrator',
'firstname': 'test',
'email': 'test#gmail.com',
'phone': '9000024100',
'surl': 'https://payu.herokuapp.com/success',
/* 'Furl' :'https://www.payumoney.com/mobileapp/payumoney/failure.php', */
'Furl': 'https://payu.herokuapp.com/failure',
'Hash': '9feaefa45b5b68c7091f7f1ff513183f3fca5b23b47d47d760c285c8ad2d5f9fd1ec9514f2bad5d3672b6cb9138af5dd5350a5cf1e87c6f20ca26817ee02ae77'
};
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", winURL);
form.setAttribute("target", winName);
for (var i in params) {
if (params.hasOwnProperty(i)) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = i;
input.value = params[i];
form.appendChild(input);
}
}
document.body.appendChild(form);
// window.open('', winName,windowoption);
form.target = winName;
console.log(form.action);
form.submit();
alert(event.type + ' - ' + event.url);
}
function iabLoadStop(event) {
alert(event.type + ' - ' + event.url);
}
function iabLoadError(event) {
alert(event.type + ' - ' + event.message);
}
function iabClose(event) {
alert(event.type);
iabRef.removeEventListener('loadstart', iabLoadStart);
iabRef.removeEventListener('loadstop', iabLoadStop);
iabRef.removeEventListener('loaderror', iabLoadError);
iabRef.removeEventListener('exit', iabClose);
}
// device APIs are available
function onDeviceReadyEWEWE() {
//form.submit();
var options = {
location: 'yes',
clearcache: 'yes',
toolbar: 'yes',
closebuttoncaption: 'DONE?'
};
iabRef = window.open('https://test.payu.in/_payment', '_blank', options);
iabRef.addEventListener('loadstart', iabLoadStart);
iabRef.addEventListener('loadstop', iabLoadStop);
iabRef.addEventListener('loaderror', iabLoadError);
iabRef.addEventListener('exit', iabClose);
}
and in my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content ng-controller="ExampleController">
Testing
<p ng-bind-html="myHTML"></p>
<button ng-click="testmethod()">button</button>
</ion-content>
</ion-pane>
</body>
</html>
so please help me out how to send form data with URL in window.open();
After Edit:
finally Integrated Inappbrowser to My Ionic app and cracked a solution.please find the URL for PayU Money Integration for Hybrid appsPayUmoneyIntegartion

$(document).ready function won't fire up

I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events

Categories