Search code examples
wcfjquerycordovawcf-rest

PhoneGap with WCF Rest Service


So I have started with PhoneGap/Cordova (windows phone) and WCF Rest Services, however, I am having problems on getting the Emulator to interact with the WCF Service.

At first I was thinking that maybe the Emulator could not connect to the localhost WCF Service, so I published the WCF Service on an external host however the problem still occured... i.e. still not able to make a call to the WCF Service.

The code I have is shown below:

The javascript file for the PhoneGap application is the following:

function getAjax() {
var jqxhr = $.ajax({
    url: 'http://link.to.service.com/service1/',
    //headers:
    beforeSend: function (xhr) {
        //xhr.overrideMimeType('text/plain; charset=x-user-defined');
    },
    dataType: 'json'
})
.done(function (data) {
    var element = document.getElementById('ajaxCall');
    element.innerHTML = JSON.stringify(data, null, "\t");
})
 .fail(function (xhr, status, error) {
     showError(error);
 })
 .always(function () { showAlert("complete"); });

}

Then the WCF Service contains the following method:

 [WebGet(UriTemplate = "")]
    public List<SampleItem> GetCollection()
    {
        return new List<SampleItem>()
                   {
                       new SampleItem()
                       {
                           Id = 1,
                           StringValue = "Hello" }
                   };
    }

Therefore, when the a call to the javascript method "getAjax" is done, the WCF Service method should be called however it keeps entering the fail function instead showing an error message 'undefined'.

Is there something that I am missing out here?


Solution

  • After further investigation, this has been resolved using the line:

    jQuery.support.cors = true;

    Just a small quote from the jQuery library for those having the same issue, this is what the above line does:

    cors is equal to true if a browser can create an XMLHttpRequest object and if that XMLHttpRequest object has a withCredentials property. To enable cross-domain requests in environments that do not support cors yet but do allow cross-domain XHR requests (windows gadget, etc), set $.support.cors = true;. CORS WD