Aouadi Adib
Aouadi Adib

Reputation: 33

Ajax request not working on cordova android Application

I have a cordova android app for showing news from a JSON web service the ajax request work on web browser but not work on android when i create the .apk file the link of the app https://github.com/Adib12/technologia

My config file

<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Technologia</name>
    <description>
        Suivre les actualités des nouvelles technologies
    </description>
    <author email="[email protected]" href="http://cordova.io">
        Aouadi Adib ( AdibDev )
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>

I need help

Upvotes: 1

Views: 4061

Answers (1)

Simon Prickett
Simon Prickett

Reputation: 4123

From the Github link you posted, it looks like you are trying to connect to a localhost URL. This won't work when running on a device, so you'll need to change that to the name of the resource you're connecting to, or its IP address (best to use DNS name).

Additionally I notice you don't have a Content-Security-Policy meta tag in the head section of your index.html - you will need one of these for Cordova 5 and higher... this specifies what resources your app can connect to. Assuming your service that you want to make an Ajax request to is running at http://myserver.mydomain.com, your CSP meta tag would need to look something like this:

<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 http://myserver.mydomain.com">

I wrote a blog post that covers set up of Content Security Policy for Android and iOS here.

Please change localhost to a valid server name in your www/js/script.js, specifically here:

$.ajax({
            type: "POST",
            url: "http://localhost/sv/connect.php",
            data: formData,
            cache: false,
            dataType: 'JSON',
            success: onSucces,
            error: onError
        });

and add a Content Security Policy meta tag to your www/index.html in the head section.

Upvotes: 1

Related Questions