reagle
reagle

Reputation: 11

Cannot send ajax request with cordova

I started new project and added code for request. My js file looks like this:

(function () {
"use strict";

document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );

function onDeviceReady() {

    $.ajax({
        type: "GET",
        url: "http://api.vk.com/method/database.getCountries?v=5.5&need_all=0",
        crossDomain: true,
        success: function (response) {
            alert('Works!');
        },
        error: function (data) {
            console.log(data);
            alert('Not working!');
        }
    });

    // Handle the Cordova pause and resume events
    document.addEventListener( 'pause', onPause.bind( this ), false );
    document.addEventListener( 'resume', onResume.bind( this ), false );

    // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
    var parentElement = document.getElementById('deviceready');
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');
    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');
};

function onPause() {
    // TODO: This application has been suspended. Save application state here.
};

function onResume() {
    // TODO: This application has been reactivated. Restore application state here.
};
})();

But it didn't work at all. It always returns "Not working". I've tried other ways to send request but always get an error. Please, help!

Upvotes: 1

Views: 1060

Answers (1)

Naitik
Naitik

Reputation: 1465

Cordova 5.0 blocks external http requests by default.

Try adding cordova-plugin-whitelist to your project.

And rebuild your app still issue persist. Do one of following:

1) set following herder in your response service:

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

2) Add this line to config file -:

<access origin="*" />

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

$.support.cors=true;

4) You can follow this $.getJSON for make request instead of ajax.

Hope it will help you.

Upvotes: 1

Related Questions