PhoneGap: unable to getJSON from a remote server - android

Using PhoneGap 2.5.0 + jQuery 1.9.1 + jQueryMobile 1.3.0, I'm trying to download a remote JSON file:
$(document).ready(function() {
$.getJSON("http://foo.mydomain.com/json.php?callback=?",function(data) {
alert("It works");
})
});
I modified 'res/xml/config.xml' to allow remote accesses to my server:
<cordova>
<access origin="http://127.0.0.1*"/>
<access origin="http://foo.mydomain.com*" />
<content src="index.html" />
But it does not work. What am I doing wrong? Thank you very much in advance.

Probably it's a problem related with Access-Control-Allow-Origin Issue.
To solve this, you should use JSON-P in the ajax request.
Try something like this:
$.ajax({
type : "GET",
dataType : "jsonp",
url : 'your-external-url',
data : {},
success: function(obj){
}
});

Related

NetworkError: Failed to execute 'send' on XMLHttpRequest': Failed to load

Server side is Django/python.
Client environment is cordova/android.
This request fails :
$.ajax({
url: myAddress,
type: 'POST',
data: mydata,
crossDomain: true,
processData: false,
contentType: false,
async: false,
success: function () { mycode},
error: function (xhr) { mycode} }
});
When myAddress is 192.168.1.11 it works perfectly.
When myAddress is dev.mysite.com i get the error:
NetworkError: Failed to execute 'send' on XMLHttpRequest': Failed to load dev.mysite.com/../..
However, i can connect to the same django web server with chrome on the mobile device.
config.xml contains : access origin="*"
Do you have an idea to solve this problem?
The js code is good.
The CSP code is good.
My problem came from my misunderstanding of http redirection at the DNS level.
Thank you for you attention

Cordova / Android web view Ajax request: 'unknown chromium error'

I have just upgraded from Cordova v3.4 to latest 6.1.1. My whole android app is working just fine apart from ALL jquery Ajax calls here is a sample one:
var baseUrl = 'http://gazetkisklepowe.pl';
$.ajax({
url: baseUrl+"/api/get/favourites",
data: {
user_uuid: device.uuid
}
}).done(function(data) {
}).fail(function() {
alert('Error connecting. (100) '+baseUrl+"/api/get/favourites");
return null;
});
I have read this article: PhoneGap / Android WebView throws "Unknown chromium error: 0" but I haven't found a solution for me.
The message in the LogCat just displays: "unknown chromium error: 0"
My config.xml contains:
<access origin="*" />
<access origin="mailto:*" launch-external="yes"/>
SN: I would like just to inform that previously on Cordova v3.4 all Ajax requests worked just fine and there have not been any changes in the code since then.
UPDATE 10am 5/04/2016
I have added whitelist plugin and <allow-navigation href="data:*" /> to the config.xml, now I get:
object has no method 'error' at file ///android_asset/www/plugins/cordova-plugin-whitelist/whitelist.js:24
Line 24 in that js file is: console.error(msg); so from some reason console is not fully defined.
UPDATE 2pm 05/04/2016
I have created new cordova app in separate folder and copied my files over, that done the trick and have fixed everything.

Google Maps Javascript API V3 getting 404 not found on mobile/native App

I can get Google Maps to show up in a browser with no problem. When I package my application up with phonegap build it does not work. In my remote debugging session it says that
https://maps.googleapis.com/maps/api/js?key=My_Key_Goes_Here
Failed to load resource: the server responded with a status of 404 (Not Found)
In the head of the doc I have:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MyKey"></script>
<script src="js/locations.js" type="text/javascript"></script>
In the network console I get:
Request URL:http://maps.googleapis.com/maps/api/js?key=MyKeyHere
Request Method:GET
Status Code:404 Not Found (from cache)
Response Headers
Client-Via:shouldInterceptRequest
Request Headers
Provisional headers are shown
Accept:*/*
User-Agent:Mozilla/5.0 (Linux; Android 5.0.2; SM-T530NU Build/LRX22G; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/46.0.2490.76 Safari/537.36
Query String Parameters
view source
view URL encoded
key: MyKeyDisplayedHere
In my config.xml file I have included these lines:
<preference name="orientation" value="portrait" />
<preference name="Fullscreen" value="true" />
<access origin="*://*.googleapis.com/*" subdomains="true" />
<access origin="*://*.gstatic.com/*" subdomains="true" />
<access origin="*://*.google.com/*" subdomains="true" />
<access origin="*://*.googleusercontent.com/*" subdomains="true" />
I am using jQuery Mobile and I am not displaying the map on the first page but another page. Regardless, it gives a 404 when trying to get from the API but here is the JS code in the locations.js file:
$(document).on('pageshow', "#map-page", function() {
var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); // Default to Hollywood, CA when no geolocation support
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
drawMap(defaultLatLng); // No geolocation support, show default map
}
function drawMap(latlng) {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
console.log('hey');
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
}
});
I have also tried changing the API's href to "http" instead of "https"
After some digging, I came upon some documentation here:
Apparently you have to add in the whitelisting plugin instead of it being native so I changed my config.xml file to this:
<access origin="http://*.phonegap.com" subdomains="true" />
<access origin="*://*.googleapis.com/*" subdomains="true" />
<access origin="*://*.gstatic.com/*" subdomains="true" />
<access origin="*://*.google.com/*" subdomains="true" />
<access origin="*://*.googleusercontent.com/*" subdomains="true" />
<plugin name="cordova-plugin-whitelist" />
It works now in the mobile app and I can use external resources that I whitelist as well.

XMLHttpRequest - empty responseText but status 200 and readyState 4

XMLHttpRequest - empty responseText but status 200 and readyState 4
I've been trying to do a cross domain request with plain JS. It does work in Firefox and Chromium but not in Android Emulator.
The onload method returns success (status 200 and readyState 4) but the responseText is empty.
window.addEventListener('load', function () {
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open('GET', 'http://10.2.1.22/'); // My website running in local apache right now. It'll be in a webhosting.
xmlHttpRequest.addEventListener('load', function () {
document.body.appendChild(document.createTextNode(this.status + " - " + this.readyState)); // output: "200 - 4"
document.body.appendChild(document.createTextNode(this.responseText)); // in browser output is a regular string ... in android emulator it's an empty string.
});
xmlHttpRequest.addEventListener('error', function (event) {
document.body.appendChild(document.createTextNode("Error!")); // it's never called.
});
xmlHttpRequest.send();
});
My website sends these headers:
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
Cordova version:
$ cordova --version
3.4.0-0.1.3
EDIT
app_root/config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.xmlhttprequest" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>XMLHttpRequest</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<author email="dev#cordova.apache.org" href="http://cordova.io">
Apache Cordova Team
</author>
<content src="index.html" />
<access origin="*" />
</widget>
Did you add your site to the whitelist in config.xml? By default, all documents that are whitelisted will return an empty document if you didn't explicitly whitelist it. This is by design. You should probably read about the whitelist:
http://docs.phonegap.com/en/3.4.0/guide_appdev_whitelist_index.md.html#Whitelist%20Guide

Phonegap Cross-domain AJAX POST Request not working on Android

Cross-domain AJAX POST request works perfectly fine on web browsers including browsers on mobile phones, but doesn't work for native applications built using Phonegap
I have created a login form that users have to enter their login credentials, then they are verified by the server that is hosted on heroku and returns json {"success":true} if valid credentials are entered.
My Ajax script:
$.ajax({
type: "POST",
url: "http://domain.com/public/auth/app-login",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
data: {identity: <username from form>, password: <password from form>},
crossDomain: true,
cache: false,
success: function(data) {
obj = JSON.parse(data);
if (obj && obj.success === true) {
window.location.href = 'home.html';
}
},
error: function(e) {
alert('Error: ' + e.message);
}
});
Steps taken to resolve this issue:
Domain whitelisting - config.xml
<access origin="http://domain.com/public/auth/app-login" />
<access origin="*" />
Telling jQuery to allow cross-domain
$.support.cors = true;
OR
jQuery.support.cors = true;
Disable caching cache: false
Any help is appreciated.
Ok. If index.html in local then you can call ajax any hosts, not need enable CORS in client or server. You remove:
$.support.cors = true; OR jQuery.support.cors = true;
And:
<access origin="http://domain.com/public/auth/app-login" />
It redundant, only use:
<access origin="*" />
You need check and add in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Add more permission if your app required. Finally, call ajax inside $(document).ready():
$.ajax({
type: "POST",
url: "http://domain.com/public/auth/app-login",
dataType: "json",
data: {identity: <username from form>, password: <password from form>},
success: function(data) {
obj = JSON.parse(data);
if (obj && obj.success === true) {
window.location.href = 'home.html';
}
},
error: function(e) {
alert('Error: ' + e.message);
}
});
If you are looking to resolve this issue then you may wish to make sure that the plugin is being properly included into the build process.
RESOURCE: \app\config.xml
<widget>
.... [lots of stuff] ....
<gap:plugin name="com.indigoway.cordova.whitelist.whitelistplugin" />
<access origin="http://*" />
....
</widget>
You may also wish to specify a version as that is recommended, and I do not specify one above. A good way to test if the plugin is included is to use the free cloud account provided at, https://build.phonegap.com/apps. If you build your project there you can check the plugins tab and make sure that the whitelist plugin is included.
I have read that you should only need this in the HEAD element of your HTML page, but I found as of the date of this post that I still needed to include the plugin.
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
If the plugin is not loaded you might get a "Not Found" error when using the $.ajax method for jQuery for the error string.
Some of the information on the Internet will tell you that the whitelist information is placed into the /www/res/ folder, but this appears to be outdated information. You may also find that <plugin... is used in some examples, but it appears that this may be an obsolete way?
Also, you may need:
RESOURCE: \app\config.xml
<widget>
...
<feature name="http://api.phonegap.com/1.0/network"/>
...
</widget>
use
JSON.stringify(data: {identity: <username from form>, password: <password from form>})
instead of
data: {identity: <username from form>, password: <password from form>}
I got success message when i changed my code like this.
Some time there is issue in your domain. In my case I resolved it by putting following code in my .htaccess file
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>

Categories

Resources