jQuery ajax json request not working over mobile network - android

Ive been scratching my head with this for a few days now.
I have written a mobile specific website using plain old html and jquery.
It used ajax with json responses to get data from a service written using service stack.
all works perfectly fine from desktop and lots of different mobile i have tried (android, iphone, bb etc)
However there seems to be a specific issue with my handset (Samsung Galaxy S2 on vodafone)
When the handset is on wifi the ajax works perfectly and the json object is received from the service and processed correctly.
However when on mobile data the response does not come back as json but as the service stack web page (it looks like its not being told to return json correctly)
Im wondering if the headers could be being stripped out by vodafone or someting?
this is the ajax call being used
$.ajax({
url: sgee.ApiUrl + "/api/GetRegionId/" + sgee.App.postcode,
type: 'GET',
dataTye: 'json',
contentType: "application/json;charset=utf-8",
cache: false,
success: function (data) {
if (data.success) {
sgee.App.EnquiryId = data.enquiryId;
sgee.App.RegionId = data.regionId;
sgee.App.RegionName = data.regionName;
$("#regionTxt").html("We have identified that you live in the " + sgee.App.RegionName + " supply region.");
sgee.EndLoading(250);
sgee.HideStep(2);
} else {
sgee.SetValidationError("#pcodeControl", "Please enter a valid UK postcode");
}
},
error: function () {
sgee.SetValidationError("#pcodeControl", "Please enter a valid UK postcode");
sgee.SendError("Error on /api/GetRegionId/", "sgee.Step1");
},
complete: function () {
}
});
This is the data expected
{"postCode":"s63","regionId":14,"regionName":"YORKSHIRE","enquiryId":578106,"success":true,"returnedId":0}
and when running on mobile this is what i am receiving (ill not include the whole as it is long but it is just the html response as if i hadnt set the response type or browsed to the page)
<!doctype html>
<html lang="en-us">
<head>
<title>GetRegionId Snapshot of 03/08/2012 13:59:50</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
This really is driving me mad as it is impossible to debug (at least i cant find a way) i am using the android chrome remote developer tools to step through code but i cant capture the http request and response as it is on the mobile network.

Just guessing... But you're expecting json content right? If so, why is your response "text/html" instead of "application/json"?

You have a typo in there... "dataTye: 'json',". Could this be it?

I think is due to type of form submission. use post instead of get...

Related

Cordova doesn't add data to URL (AJAX)

I'm sending an Jquery.Ajax request to a server which is hosting a .asmx web service.
jQuery.ajax({
type: 'GET',
url: 'http://IP-destination/myFolder/WebService.asmx/LogonUser',
cache: 'true',
data: {
'username':get_cookie('username'),
'password':get_cookie('password'),
'environment':get_cookie('environment')
},
dataType: 'jsonp',
beforeSend: function(){$.mobile.loading('show', 'a', 'Laddar...', false); alert("go");},
error: function(a, b, c){
$.mobile.loading('hide','a');
alert(a + b+ c);
},
success: function(response){
$.mobile.loading('hide','a');
alert("success");
self.loginUser_cb(response);
}
});
While sending data through my browser, emulator or "Legacy Hybrid build (Intel XDK) for android" everything works great.
But when I use Cordova (still android, works on IOS) the request get an "500 Internal Server Error".
It seems like my URL is missing my data parameters:
http://oi60.tinypic.com/21jvb5y.jpg
When I use my browser the URL is correct with the data parameter in the end of the url: /LogonUser?callback=jQuery19105695250731240461_1425028837473&username=MyUserName&password=Secret&environment=Dev
My question is: What could possibly cause this in Cordova Android but work great
in the emulator/ios/Hybrid Legacy build? The URL seem to be cut short.
I'd look to simplify things as much as possible and see if the get_cookie portion is failing for you. Try removing that and using static values. If it works, it means your cookies may not exist as you think they should and you should write logic to handle that.

POST : angularjs app to cakephp site

I put this add action in my spoutnik controller like the REST doc of cakephp :
public function add() {
$this->layout = null;
$this->autoRender = false;
if ($this->Spoutnik->save($this->request->data)) {
$message = array(
'text' => __('Saved'),
'type' => 'success'
);
} else {
$message = array(
'text' => __('Error'),
'type' => 'error'
);
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
I put this JS part in my angularjs app (actually in a other domain than the cakephp site):
<form ng-controller="MessageController" ng-submit="createMessage()">
<legend>Create Message</legend>
<label>Title</label>
<input type="text" id="name" name="name" ng-model="message.name" placeholder="Title">
<label>Message</label>
<input type="text" id="email" name="email" ng-model="message.email" placeholder="ur message here">
<button class="btn btn-primary">Add</button>
</form>
and
function MessageController($scope, $http) {
$scope.message = {};
$scope.createMessage = function() {
$http({
method : 'POST',
url : 'http://www.mycakephpdomain.com/spoutnik/add',
data : $scope.message
})
}
}
Nothing work... i have no errors in chrome console, i'm totally lost :/ I just want to build an android app in angularjs with no java or PHP, and post to my cakephp website. For the moment, i try to post form an other domain (i can't touch apache configuration).
What is wrong in my code ?
Just for the record and debugging purposes:
I did not find the reason to this same problem, but looking the AJAX request done by AngularJS I found that message data from the form was no being sent as regular form data. Instead it was being sent as REQUEST PAYLOAD.
Indeed, the response from the server contained this error just before the JSON response from my view:
Warning (4096): Argument 1 passed to Hash::get() must be of the type
array, null given, called in
/var/www/test/lib/Cake/Network/CakeRequest.php on line 866 and defined
[CORE/Cake/Utility/Hash.php, line 44]
Of course, i checked that there was nothing strange by my side executed, I even tried disabling all security component and allowing AUTH *.
If you set the core.debug in php to 0, the error wont be shown and
everything will be ok, but thats not what you want for your awesome
app.*
I changed query data from $scope.message to just $('form').serialize(), but still no way.
So finally, the only solution I found was to remove the $http.post and replace it by a very know $.ajax() which just did its job as always...
So thats my suggestion, remove the $http.post and user common jQuery.ajax();
There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.) The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively ... By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
So concretely, your $_POST variable is empty !
To go through this problem there're 2 solutions:
Change the data format in Angular config
Change the way to get the datas with PHP(Deprecated but works)
I haven't invented anything here, just linking...
Hope it'll help.

PhoneGap App: jQuery getJSON getting 404 error when getting local file with relative URL

I have an HTML/JavaScript app that I'm trying to convert to an App using PhoneGap via the Phonegap Build app
Everything works fine through the browser, and the only problem the app is having is that the call to getJSON is returning a 404 error when trying to load my local resources.
Here is the culprit:
$.getJSON( "./shapes/json/" + abbr + '.json', gotJSON(abbr) );
I have whitelisted every domain, just to be sure:
<access origin="*" />
Is this something that is not possible from the phonegap environment? Or am I doing something wrong?
If needed, I can host the files elsewhere and do a cross-domain ajax call, but I'd rather have the files right there on the device.
This is currently happening on Android, which is the only system I can test at the moment.
UPDATE:
I'm now trying:
var xhrShapes = new XMLHttpRequest(), xhrSuccess = gotJSON(abbr);
xhrShapes.open('GET', config.path + "/shapes/json/" + abbr + ".json");
xhrShapes.onreadystatechange = function(e){
if( this.readyState === 4 ){
if( this.status === xhrSuccessCode ){
xhrSuccess(JSON.parse(this.responseText));
}
}
}
xhrShapes.send();
config.path is "file:///android_asset/www" and I'm getting 0 as a success code (which indicates success for 'file://' requests). but xhrShapes.responseText is blank and everything stops at the call to JSON.parse. I feel like I'm missing something simple...
The problem had nothing to do with the code, but rather with the file names being case-sensitive... my abbr variable was uppercase, but filenames are lowercase. $.getJSON works perfectly, now that I've corrected this (though now my pride needs some repairs).

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

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
Are you sure that BlueStacks uses the same host IP (10.0.2.2) as the emulator? I'm not familiar with it so I'm not sure what the answer to that is.
jQuery wants the data to be a string, try:
data: JSON.stringify({'EncryptedPassword':'1234','UserName':'test','DeviceToken':'d234'});
and for good measure, add
contentType: 'application/json',
in your ajax settings.
To anyone who ever looks this up, the issue ended up being the port that IIS Express was using on my local machine. When I got things to route through port 80, everything worked okay.

AJAX to Sharepoint Server with Phonegap and JQuery Mobile not working

I have the following Problem. In the Phonegap App(for Android) I want to make an AJAX-Call to connect with a Sharepoint Server, with the following Code:
$.ajax({
url:"https://xxx/_vti_bin/lists.asmx",
beforeSend: function( xhr ){
xhr.setRequestHeader(
"SOAPAction",
"http://schemas.microsoft.com/sharepoint/soap/GetListCollection"
);
xhr.setRequestHeader("Content-Type","text/xml; charset=utf-8");
},
dataType:"xml",
contentType: "application/xml; charset=utf-8",
timeout:10000,
type:'POST',
cache: false,
username: "username",
password: "password",
data: soapEnv,
success:function(data) {
// alert data
var serializer = new XMLSerializer();
serialized = serializer.serializeToString(data);
alert(serialized);
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
// alert errors
alert("Error status :"+textStatus);
alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
alert("Error statustext :"+XMLHttpRequest.statusText);
alert("Error request status :"+XMLHttpRequest.status);
},
complete: function(jqXHR, textStatus){
alert(textStatus);
}
});
When I try to run it on the Android Emulator the error messages are:
Error status: error
Error type:
Error message: undefined
Error statustext: error
Error request status: 0
However when I try to run it on my Browser (Chrome) with disabled websecurity (because of same origin policy) it works all fine. Phonegap normally shouldn't care about SOP because of the file:/// Protocol. I added the following to 'mobileinit':
$(document).bind("mobileinit", function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
But when I run the same Code in Chrome without websecurity disabled, I get exactly the same errors as in the Android Emulator.
I also tried an AJAX call to wikipedia (with html instead of xml, and GET instead of POST), and that worked without a problem.
Also I think the AJAX to Sharepoint doesn't even get fired (no traffic in Fiddler2, if I managed to configure it the right way)
So I am really stuck with this problem since 2 days now, if anyone knows how to make this ajax call work, it would made me so happy :-)
(soapEnv is the XML envelope, sent to the server)
Well I know that once upon a time jQuery had a bug where it treated a request status of 0 as an error. When running from the file protocol a status of 0 is the same this as a 200 (OK). You may need to update your version of jQuery.
Alternatively to test my theory just do a plain vanilla XHR request to your service to see if it works. Here is my stock example:
http://simonmacdonald.blogspot.com/2011/12/on-third-day-of-phonegapping-getting.html

Categories

Resources