0

I am trying to extract products in a web service (prepared by my PrestaShop website), using WAMP (in local so).

My code : index.js

var app = {

  initialize: function() {
    this.bindEvents();
  },

  bindEvents: function() {
    this.onDeviceReady();
  },

  onDeviceReady: function() {
    var password = '';
    var key = 'F51Q7VWPRREG7TA25DEY8UIZT8V79E5V';
    var url = 'http://localhost/Test/prestashop/api/products?PHP_AUTH_USER="password"&ws_key="key"';

    $.ajax({
      type: "GET",
      dataType: "xml",
      url: url,
      success: this.onSuccess(data),
      error: this.onErreur()
      }); 
  },

  onSuccess: function(data) {
    alert("Success");
  },

  onErreur: function() {
    alert("Error");
  }
};

app.initialize();

![enter image description here][1]

I tried to replace localhost with my IP but it doesn't success yet. I have not alert "Success" or "Error". I don't understand why. I searched a lot of things, whitout success.

EDIT :

config.xml

<name>webService</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" />

<plugin name="cordova-plugin-whitelist" version="1" />

<allow-navigation href="http://prestashop/api/products?ws_key=F51Q7VWPRREG7TA25DEY8UIZT8V79E5V&output_format=JSON" />

<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>

index.html

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' http://prestashop/api/products?ws_key=F51Q7VWPRREG7TA25DEY8UIZT8V79E5V&output_format=JSON 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="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" href="bower_components/ratchet/dist/css/ratchet.min.css" media="all">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <title>Web Service</title>
</head>

<body>
    <div class="app">
        <h1>Apache Cordova</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>
        </div>
        <button id="btnCharge" class="btn btn-primary btn-block">Charger Web Service</button>

    </div>

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script>
    <script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
</body>
</html>

index.js

var app = {
  initialize: function() {
    this.bindEvents();
  },

  bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
  },

  onDeviceReady: function() {
    app.receivedEvent('deviceready');

    $('#btnCharge').click(function(e){
      //alert("btnCharge");
      checkWebService();
    });
  },

  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();




function checkConnection() {
  var networkState = navigator.connection.type;

  var states = {};
  states[Connection.UNKNOWN]  = 'Unknown connection';
  states[Connection.ETHERNET] = 'Ethernet connection';
  states[Connection.WIFI]     = 'WiFi connection';
  states[Connection.CELL_2G]  = 'Cell 2G connection';
  states[Connection.CELL_3G]  = 'Cell 3G connection';
  states[Connection.CELL_4G]  = 'Cell 4G connection';
  states[Connection.CELL]     = 'Cell generic connection';
  states[Connection.NONE]     = 'No network connection';

  //alert('Connection type: ' + states[networkState]);
}


function checkWebService() {
  checkConnection();
  var networkState = navigator.connection.type;

  if (networkState == Connection.NONE) {
    alert("Pas de connexion");
  } 
  else  {

    var key = 'F51Q7VWPRREG7TA25DEY8UIZT8V79E5V'; //http://prestashop/api/products?ws_key=F51Q7VWPRREG7TA25DEY8UIZT8V79E5V&output_format=JSON
    var url = 'http://prestashop/api/products?ws_key=' + key + '&output_format=JSON';

    $.ajax({
      url: url,
      dataType: 'json',
      type: 'GET',
      success: function (products) {
        alert("Success GET JSON" + products);
      },
      error: function (jqXHR, exception) {
        if (jqXHR.status === 0) {
          alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404) {
          alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500) {
          alert('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
          alert('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
          alert('Time out error.');
        } else if (exception === 'abort') {
          alert('Ajax request aborted.');
        } else {
          alert('Uncaught Error.\n' + jqXHR.responseText);
        }
      },
    });
  }
}

I tried index.html and index.js with my Browser and it works.

Stalyon
  • 538
  • 5
  • 20
  • Does your application have the permission for accessing the `INTERNET`? Also, could you post post the debug log? Use ADB to view the debug log using: adb logcat CordovaLog:D *:S in CLI. Alternatively, you can use Chrome's remotely debugging a WebView facility if you have a device having Anrdoid 4.4+(Kitkat or higher) - https://developer.chrome.com/devtools/docs/remote-debugging – Keval Jun 09 '15 at 10:34

2 Answers2

1

I had quiet the same issue.

I do agree with @Keval, you probably doesn't have the permission to access to the internet.

Add this plugin https://github.com/apache/cordova-plugin-whitelist and go to your config.xml file. In this one, just att this line, with your IP adress of course :

<allow-navigation href="http://xxx.xxx.xxx.xxx/*" />

This may solve it, because the <access origin="*" /> isn't enough. (At least, wasn't enough for me)

Guillaume Munsch
  • 1,233
  • 17
  • 37
  • I tried this. No results. Do you have any examples to help me ? – Stalyon Jun 10 '15 at 13:01
  • Yes, it works. I changed some stuffs in my code. I edit my first post with all my code. (thx for your help) – Stalyon Jun 10 '15 at 13:18
  • So, now, what's the output of the App, do you get a "Success" or an "Error" ? And do you mind post here the `allow-navigation`line you added in your file (With xxx.xxx.xxx.xxx for the IP adress ofc) – Guillaume Munsch Jun 10 '15 at 13:21
  • I puted my codes on the first post. The alert I have is : "Not connect. Verify Network." – Stalyon Jun 10 '15 at 13:23
  • Try to change this `` to this `` – Guillaume Munsch Jun 10 '15 at 13:27
  • And, i suppose you hav your IP in here `http://[YOUR IP]/prestashop/api/products?ws_key=F51Q7VWPRREG7TA25DEY8UIZT8V79E5V&output_format=JSON` ? – Guillaume Munsch Jun 10 '15 at 13:28
  • I tried it before and no results. About my IP, I configured a virtual host (with Wamp). I tested it and no problem. – Stalyon Jun 10 '15 at 13:31
  • Well, the accessibility seems OK to me, as your output says it, it's probably a network reachability problem. You're testing from a device, or through the navigator / Ripple ? – Guillaume Munsch Jun 10 '15 at 13:36
  • With Android Emulator. It seems Ripple doesn't work with the last version (the device is never "ready"). – Stalyon Jun 10 '15 at 13:37
  • Run `cordova serve` in your project folder. It's supposed to launch your project in a browser tab. If this works, it's simply that the android emulator doesn't have access to the internet. – Guillaume Munsch Jun 10 '15 at 13:39
  • + just add a `button` in your main page to activate manually the `checkWebService()` function – Guillaume Munsch Jun 10 '15 at 13:40
  • When I try with Ripple (putting the activation of checkWebService() outside onDeviceReady()), I have no alert (just one saying me I clicked on the button). – Stalyon Jun 10 '15 at 13:49
  • Nop, deactivate Ripple for the requests, they're failing. Just launch it in the browser without ripple. (You can see the Ripple error in the console btw) – Guillaume Munsch Jun 10 '15 at 13:50
  • Your android emulator just doesn't have access to the internet. If you have an android device, install the .apk on it and it'll work finely ! ;) (Entre français, on s'aide ;) ) – Guillaume Munsch Jun 10 '15 at 13:53
  • I only have an iPhone (but not a Mac), so I can't test directly with a device ... (Merci en tout cas, c'est gentil ;) Moi qui ait du mal en anglais depuis tout à l'heure en plus :P) – Stalyon Jun 10 '15 at 13:56
  • Look at some posts like this one : http://stackoverflow.com/questions/2039964/how-to-connect-android-emulator-to-the-internet ;). – Guillaume Munsch Jun 10 '15 at 13:57
  • Ok, I tried to access directly with the Emulator's Browser on my URL and it doesn't work ... – Stalyon Jun 10 '15 at 14:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/80191/discussion-between-stalyon-and-lezohan68). – Stalyon Jun 10 '15 at 14:01
  • It's just to verify ;) Well, hope everythin's alright now ! See you :) – Guillaume Munsch Jun 10 '15 at 14:02
0

To resolve my problem (connecting Android Emulator to Wamp (local)), I follow this tutorial : http://www.bradcurtis.com/hosts-files-and-the-google-android-emulator/

Stalyon
  • 538
  • 5
  • 20