Ron Harlev
Ron Harlev

Reputation: 16673

AJAX Request from Phonegap Android fails

I have been working on this for the last two days, and looking at a lot of other suggestions. Yes I can get this simple ajax request to work from within a phonegap application, both on the android emulator and on an actual android phone.

My phonegap version is (using phonegap -v) 3.0.0-0.14.3

The code I'm using is:

var url = 'http://www.thomas-bayer.com/sqlrest/CUSTOMER';
    return $.ajax({
        type: "GET",
        url: url,
        timeout: 60 * 1000
    }).done(function (data) {
        alert('hey');
    }).fail(function (a, b, c) {
        console.log(b + '|' + c);
    });

The result I'm getting in the log is just:

error| at file:///android_asset/www/js/index.js:62

I added the settings to the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

and I have the following in Config.xml

<param name="android-package" value="org.apache.cordova.core.NetworkManager" />

When I check navigator.connection.type I get 3G on the emulator and wifi on the physical phone.

Any idea what else could go wrong?

UPDATE: If I log the JSON in the first parameter of the failing function I get:

{"readyState":4,"status":404,"statusText":"error"}

Upvotes: 24

Views: 47444

Answers (3)

Sabel
Sabel

Reputation: 589

I had a localhost url as I was using Visual Studio. I resolved by editing the VS projects Applicationhost.config file and making a version of the binding protocol so that is it :port: not *:port:localhost, and then accessing via ip address. Make sure to get all references to the port.

Upvotes: 0

akiva
akiva

Reputation: 2737

additionally to the whitelisting, make sure the cors flag is true to enable cross origin resource sharing.

$.support.cors=true;

please find the reference here

Upvotes: 16

Raoul George
Raoul George

Reputation: 2797

You should whitelist the domain in order for your AJAX calls to work.

Add this line to config file -:

<access origin="*" />

Phonegap's default policy blocks all network access unless specified otherwise. The above line will disable this security restriction. You can also be more specific in allowing only certain domains to bypass this security feature by including the domain name in the config file like so

<access origin="http://yourdomain" />

Upvotes: 48

Related Questions