Trouble getting $.ajax() to work in PhoneGap against a locally hosted server

Posted by David Gutierrez on Stack Overflow See other posts from Stack Overflow or by David Gutierrez
Published on 2012-06-26T19:37:27Z Indexed on 2012/10/12 15:37 UTC
Read the original article Hit count: 323

Filed under:
|
|
|
|

Currently trying to make an ajax post request to an IIS Express hosted MVC 4 Web API end point from an android VM (Bluestacks) on my machine. Here are the snippets of code that I am trying, and cannot get to work:

    $.ajax({
        type: "POST",
        url: "http://10.0.2.2:28434/api/devices",
        data: {'EncryptedPassword':'1234','UserName':'test','DeviceToken':'d234'}
    }).always(function( data, textStatus, jqXHR ) {
        alert( textStatus );
    });

Whenever I run this request I always get back a textStatus of 'error'. After hours of trying different things, I pushed my End Point to an actual server, and was able to actually get responses back in PhoneGap if I built up an XMLHttpRequest by hand, like so:

var request = new XMLHttpRequest();
        request.open("POST", "http://172.16.100.42/MobileRewards/api/devices", true);
        request.onreadystatechange = function(){//Call a function when the state changes.
            console.log("state = " + request.readyState);
            console.log("status = " + request.status);
            if (request.readyState == 4) {
                if (request.status == 200 || request.status == 0) {
                    console.log("*" + request.responseText + "*");
                }
            }
        }
request.send("{EncryptedPassword:1234,UserName:test,DeviceToken:d234}");

Unfortunately, if I try to use $.ajax() against the same end point in the snippet above I still get a status text that says 'error', here is that snippet for reference:

    $.ajax({
        type: "POST",
        url: "http://172.16.100.42/MobileRewards/api/devices",
        data: {'EncryptedPassword':'1234','UserName':'test','DeviceToken':'d234'}
    }).always(function( data, textStatus, jqXHR ) {
        alert( textStatus );
    });

So really, there are a couple of questions here.

1) Why can't I get any ajax calls (post or get) to successfully hit my End Point when it's hosted via IIS Express on the same machine that the Android VM is running?

2) When my end point is hosted on an actual server, through IIS and served through port 80, why can't I get post requests to be successful when I use jquery's ajax calls? (Even though I can get it to work by manually creating an XMLHttpRequest)

Thanks

© Stack Overflow or respective owner

Related posts about android

Related posts about jQuery