Confusing jQuery/ jsonp failure on Android emulator - android

I'm trying to call a service using jsonp on the andriod emulator:
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
receivedEvent: function(id) {
console.log('Received Event: ' + id);
$.ajaxSetup ({
cache: false
});
$.ajax({
type: "GET",
url: "http://10.0.2.2/uk-en/login/user",
dataType: "jsonp",
contentType: "application/json",
success: function(xml){
$("#result").html('123');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$("#result").html('XMLHttpRequest = ' + JSON.stringify(XMLHttpRequest) + ", textStatus = " + textStatus + ', errorThrown = ' + JSON.stringify(errorThrown));
}
});
}
I'm doing this on the HelloWorld app create following documentation on the phonegap site. My index.html is similar to this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<title>Hello World</title>
</head>
<body>
<div class="app">
<div id="result">
</div>
</div>
<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
This is the error I receive although this works from Firefox on my local machine:
XMLHttpRequest = {"READYSTATE":4,"STATUSTEXT":"SUCCESS"},TEXTSTATUS = PARSERERROR, ERRORTHROWN = {"MESSAGE":JQUERY1830456564654_32131 WAS NOT CALLED", "STACK":"ERROR:JQUERY1830456564654_32131 WAS NOT CALLED"\N AT FUNCTION.ERROR(http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js:2:13215)
Anyone able to help please?

JSONP requires that the response be wrapped in some kind of callback function.
This is all assuming you're grabbing the content from another domain. If so, you're limited by the same origin policy:
So the server should respond with:
urFunction({....});

Related

Maintaining temporary data across pages in phonegap using jquery mobile

I am learning to develop mobile app using Phonegap and jquery mobile.
I have the main page with a list (index.html).
If user taps on an item, it should go on the next page.
Now this next page takes the id of the item, and the next page (a separate html file, second.html) contains the details related to this item.
So I need to know the id of the item tapped on the main page, and this second.html should display data accordingly.
What I want to know is, what do I use to pass the id from main page to second page? I am currently trying to pass data by using GET parameter (second.html?id=xyz), but don't know how to catch it on the second page.
I also read a method using localstorage, But i am not sure if that is a good idea, considering this will go on with the user going to third page, fourth page, and so on. so there'll be a lot of data saving into the local storage.
First page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" type="text/css" href="js/Jquery/jquery.mobile-1.4.5.css" />
<title>Restaurant App</title>
<script type="text/javascript" src="js/configs/server.js"></script>
<script type="text/javascript" src="js/Jquery/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/Jquery/jquery.mobile-1.4.5.js"></script>
</head>
<body>
<div data-role="page" id="local">
<div data-role="main" class="ui-content">
<h2> Nearby Restaurants</h2>
<ul data-role="listview" data-inset="true" id="nearbyrestaurs">
</ul>
<script type="text/javascript">
var li = "";
$.getJSON(hostname + "/restaurants/?format=json", function(data) {
$.each(data, function(item, value) {
li = "<li><a rel=external href='menu.html?restid=" + value["id"] + "'>";
li += "<img src='";
li += hostname;
li += value["dp"];
li += "' class='ui-li-icon'>";
li += value["name"]
li += "</a></li>";
$("#nearbyrestaurs").append(li).listview('refresh');
});
})
</script>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" type="text/css" href="js/Jquery/jquery.mobile-1.4.5.css" />
<title>Restaurant Menu</title>
<script type="text/javascript" src="js/configs/server.js"></script>
<script type="text/javascript" src="js/Jquery/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/Jquery/jquery.mobile-1.4.5.js"></script>
</head>
<body>
<div data-role="page" id="menupage">
<script type="text/javascript">
</script>
<div data-role="main" class="ui-content">
<h2> Menu</h2>
<ul data-role="listview" data-inset="true" id="Menus">
</ul>
<script type="text/javascript">
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(location.search);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
}
var li = "";
restid = $.urlParam('restid');
$.getJSON(hostname + "/menus/?format=json&restid=" + restid, function(data) {
$.each(data, function(item, value) {
li = "<li><a href='";
li += "#"
li += "' class='ui-li-icon'>";
li += value["name"];
li += "</a></li>";
$("#Menus").append(li).listview('refresh');
});
})
</script>
</div>
</div>
</body>
</html>
You can use location.search:
var params = location.search;
Params will have ?id=xyz. After that you can parse the string to obtain what you want.
Here is a related question :
Passing Data between pages with JQuery Mobile
You have a function like this already:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Usage:
var yourId = getParameterByName('Id');
Maybe, your specific case could be:
$.getJSON(hostname + "/menus/?format=json&restid=" + $.urlParam('restid'), function(data) {
Or possibly:
$.getJSON(hostname + "/menus/?format=json&restid=" + getParameterByName('restid'), function(data) {

Phonegap detect backButton event fail

When I use https://build.phonegap.com/ to build my application in android, my code to process the detection of the back button does not work.
Though I have used the following code to do it :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.1.min.css">
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/jquery210.js"></script>
<script type="text/javascript" src="js/engine2.js"></script>
<script type="text/javascript" src="js/jqm141.js"></script>
<script type="text/javascript">
function onLoad(){
document.addEventListener('deviceready', function() {
navigator.splashscreen.show();
document.addEventListener("backbutton", ShowExitDialog, false);
}, false);
}
function ShowExitDialog() {
if (navigator.notification) {
navigator.notification.confirm(
("Are you sure ?"),
alertexit,
'Exit',
'Yes,No'
);
}
}
function alertexit(button){
if(button=="1" || button==1){
navigator.app.exitApp();
}
}
</script>
</head>
<body onLoad="onLoad()">
...
</body>
</html>
I get when pressing the back button, my application does not respond to anything. How do I add a detection function to Back button??
Use this simple code...
document.addEventListener("deviceready", appReady, false);
function appReady()
{
document.addEventListener('backbutton', function(e){
if (confirm("Press a button!"))
{
alert("You pressed OK!");
navigator.app.exitApp();
}
else
{
alert("You pressed Cancel!");
}
}, false);
}

using ng-views in PhoneGap getting Origin is not allowed by Access-Control-Allow-Origin

I am trying to get ng-views to work in android phoneapp app. I get the following
error when I trying to navigate to one of the views via hyperlink.
"Origin is not allowed by Access-Control-Allow-Origin"
I have tried modifying the the cordova,xml in the res folder with no luck.
From
<access origin="http://127.0.0.1*"/> <!-- allow local pages -->
To
<access origin="*"/>
Any advice is appreciated, below is the code.
Thanks.
HTML:
<html ng-app="AngApp">
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Minimal AppLaud App</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="angular.js"></script>
<script type="text/javascript" charset="utf-8" src="app.js"></script>
<script type="text/javascript" charset="utf-8">
var onDeviceReady = function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
// The message from the service is appearing, so Angular seems
// to be working fine without having to bootstrap it.
//angular.bootstrap(document, ['AngApp']);
};
function init() {
document.addEventListener("deviceready", onDeviceReady, true);
}
</script>
</head>
<body onload="init();" id="stage" class="theme">
<h2>Angular App</h2><br/>
View1
View2
<hr/>
<div data-ng-controller="MainCtrl">
<p>{{Message}}</p>
<input type="text" data-ng-model="Message"/>
</div>
<hr/>
<div data-ng-view></div>
</body>
</html>
APP.JS:
var angApp = angular.module('AngApp',[]);
angApp.config(function ($compileProvider){
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
});
angApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: TestCtrl1,
templateUrl: 'view1.html'
})
.when('/view', {
controller: TestCtrl2,
templateUrl: 'view2.html'
});
});
angApp.factory('myService',function(){
return 'I am a service';
});
function MainCtrl($scope, myService){
$scope.Message = 'This is the main controller. '+ myService;
}
function TestCtrl1($scope){
$scope.Message = 'This is controller 1.';
}
function TestCtrl2($scope){
$scope.Message = 'This is controller 2.';
}
You are missing a # sign there in href="#/view".

Phonegap + Jquery mobile on Android: Multiple HTML Pages Javascript not working

Javascript does not work outside index.html page:
Project Test 1:
Index.html (with GEOLOCATION PAGE CODE) works fine
Project Test 2:
Index.html (with MENU PAGE CODE)
Geolocation.html (with GEOLOCATION PAGE CODE) javascript does not work
The page Geolocation.html opens up, but javascript does not run.
What am i missing?
GEOLOCATION PAGE CODE:
<!DOCTYPE html>
<html>
<head>
<!-- <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />-->
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" charset="utf-8" src="js/cordova-2.5.0.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Ready...';
navigator.geolocation.getCurrentPosition(onSuccess, onError, { maximumAge: 3000, timeout: 10000, enableHighAccuracy: false });
}
function onSuccess(position) {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Success...';
initialize(position.coords.latitude, position.coords.longitude);
}
function onError(error) {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Error...';
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function initialize(latitude, longitude) {
var mapOptions = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function onBodyLoad(){
alert("test!");
}
</script>
</head>
<body>
<h2>Location</h2>
<p id="geolocation">Finding geolocation...</p>
<p id="geoTemp"></p>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
MENU PAGE CODE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.3.0.css">
<link rel="shortcut icon" href="favicon.ico">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
<script type="text/javascript" src="js/cordova-2.5.0.js"></script>
</head>
<body>
<div data-role="page" id="pageMain">
<div data-role="header">
<h1>
TestPage
</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li><a href="geolocation.html" data-transition="slide">
<h2>Geolocation Test</h2>
<p>Testing</p>
</a></li>
</ul>
</div>
</div>
</body>
</html>
I have also tried to add an onload function to the body tag and call a test function but it didn't work either.
In the link to geolocation.html, add this attribute data-ajax="false". This will prevent jQuery from loading the page via Ajax.

Phonegap my geolocation on google maps

I am using cordova 2.0.0 and i am testing on android 2.2
I want to make an app which gets my geolocation and shows it in google maps.
Now i tried my code and when i run it, it shows my coördinates but it doesn't show a map when i clicked ok.
These are my permissions:
<access origin="http://127.0.0.1*"/> <!-- allow local pages -->
<access origin="http://google.com*" />
<access origin="http://maps.google.com*" />
<access origin="https://google.com*"/>
<access origin="https://maps.google.com*"/>
If anyone could tell me what i did wrong i would greatly appreciate it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Beer Me</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError,{'enableHighAccuracy':true,'timeout':10000});
}
//GEOLOCATION
var onSuccess = function(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n');
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
//MAP
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body onload="onLoad()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
Try this src , it works for me with your same code !

Categories

Resources