Second (similar) AJAX request is not called on Android device - android

I am making an jQuery Mobile and PhonGap app. It connects to the server-side web-services by AJAX calls using JSONP (I know about cross-domain issues, although my android dev does not suffer it). I am using PhoneGap Build to prepare an application for many operating systems.
Here is my problem:
I made a index.html that makes an AJAX call to server. I am getting an response and I am redirected to main.html. It works fine on chrome, safari and my Android device.
On the second site: main.html, I have similar request (I also tried with the same request) which doesn't get called on Android device. However it works fine on both Chrome and Safari.
I tried switching off cache, proper permissions are granted, is added to config.xml. Note that I also tried to compile my app by eclipse, and with no result I added to /res/xml/cordova.xml.
I checked server logs, there are no requests from the second site. Here is the code:
Note: I also read jQuery mobile docs according to PhoneGap. Changing $(document).ready doesn't solve the problem. This construction works on index.html site.
$( document ).bind( "mobileinit", function(){
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.mobile.loadingMessageTextVisible = true;
$.mobile.showPageLoadingMsg();
console.log('Start Strony');
})
$( document ).ready(function (){ //
$.ajaxSetup ({
cache: false
});
console.log('Start');
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://ip/services/rest/contact/list',
callback: 'jsonpCallback',
jsonpCallback: 'jsonpCallback',
jsonp: '_jsonp',
scriptCharset: "utf-8",
contentType: 'application/json',
dataType: 'jsonp',
timeout : 5000,
success: function(data){
var html ='';
console.log('Success');
$.each(data.response, function(key, value) {
html += '<li><a class=contact href="#" id="' + data.response[key].id + '" ><h1>' + data.response[key].label + '</h1><p>'+ data.response[key].customerName + '</p><p>' + data.response[key].phone + ', ' + data.response[key].email + '</p></a></li>';
$('#ul_id').append($(html));
html='';
console.log('conatct');
});
$('#ul_id').trigger('create');
$('#ul_id').listview('refresh');
//localStorage.setItem('idCustomerValue', data.re);
},
error: function (xhr, ajaxOptions, thrownError){
alert("Status: " + xhr.status + ", Ajax option: " + ajaxOptions + ", Thrown error: " + thrownError);
//location.reload();
console.log('Blad');
},
});
});
Unfortunately, I cannot provide you server side code. Server is setup properly. As I mentioned Chrome and Safari work.

The problem was pageinit event and specific behaviour while linking in JQM.

Related

Cannot send cross domain requests with Cordova. Whitelisting doesn't work

I cannot make cross domain request using Cordova. Spent several hours on this and still not sure what is wrong. Maybe someone has dealt with problem like this? Thanks!
.js file:
//works fine, test.html - local file
$.get("test.html",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
//does not do anything
$.get("http://www.stackoverflow.com",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
Project Config file:
..
<access origin="stackoverflow.com"/>
..
Also Tried:
<access origin="www.stackoverflow.com"/>
<access origin="http://www.stackoverflow.com"/>
<access origin="*"/>
AndroidManifest.xml:
..
<uses-permission android:name="android.permission.INTERNET" />
..
I was having the same problem... after some researches I found a way to do this.
Use the jQuery $.ajax to make a "GET" request.
(In reality, I was trying to access a SOAP WebService, then I found this way to use a POST or GET request)
Test here in the JSFiddle.
You still need the access origin though...
Obs: Your request will not work, unless the page you are trying to get, allow you to do this. The example page allow the access, so... try accessing it from your Cordova app.
$.ajax({
type: 'GET',
url: "http://anytime.ueuo.com/http-return.php",
crossDomain: true,
success: function (data, textStatus, jqXHR) {
alert("Ok!");
$("#retorno").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Wait, take a look: " + textStatus + ", " + errorThrown);
},
complete: function (jqXHR, textStatus ) {
alert("Status: " + textStatus);
}
});
Obs-2: Your code return the error:
XMLHttpRequest cannot load http://www.stackoverflow.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. (02:18:52:813 | error, javascript) at public_html/index.html. That's why you need to test with a pre-configured page.
Sorry for my bad-english '-'

Android 2.2.3 unable to call SAML URL with JQUERY AJAX

I've been stuck here for quite some time now. I am developing a mobile application with phonegap. I have tested the app with android 4.0.4 and it is working perfectly fine. However, when I tested on 2.2.3, the AJAX ended with and error state of:
ready state = 0
HTTP Status = 0
I have tried to increase the timeout to be really long but it still ends with that result. I am not sure what is the problem but I have developed another app using the same ajax call and it is working fine on android 2.2.3 but what makes this time different is that it calls to a SAML URL (Identity Provider).
the codes is like bellow:
$.ajax({
url: "...."+Math.random(),
type: "POST",
data: {
j_username: uname,
j_password: pword
},
cache: false,
timeout: (100*1000),
success: function(data, textStatus, jqXHR){
var contentType = jqXHR.getResponseHeader('Content-Type');
if (contentType == 'application/atomsvc+xml'){
}else{
alert(".....");
// clearTimeout(timer);
$.mobile.hidePageLoadingMsg();
enableAllButtons();
}
},
error: function(jqXHR, textStatus, errorThrown){
// clearTimeout(timer);
alert("Error Thrown : " + errorThrown);
alert("status : " + jqXHR.status + " " + jqXHR.statusText);
alert("ready state : " + jqXHR.readyState);
alert(".......");
$.mobile.hidePageLoadingMsg();
enableAllButtons();
}
});
Really hope someone can help me with this.
Thank you very much for your input in advance.
Regards,
Amanda
The code seems to be fine except one thing
You are using Math.random() in the URL.. You also use cache:false
Try to remove the Math.random() from URL while jQuery Cache uses the same thing.
Also, while you get readyState = 0 then it will be a CrossDomain issue. Use JSONP for that (dateType:'JSONP') in AJAX options

cross domain ajax works in all but android

I have literally lost hair over the last 2 and a half days i've spent on this problem...
Using phonegap to build an app for iPhone and Android. Cross domain ajax works in my browser and also on iPhone. it will NOT work on Android.
I have not been using jQueryMobile, just jQuery, until i read somewhere that i should be using the mobile version to get cross domain to work on android. So i've changed up the project to suit jMobile. Do i really need to use JqueryMobile in order to get cross domain ajax working?? i would much rather not use it if possible.
tried changing things like $.mobile.allowCrossDomainPages=true; $.support.cors = true; to no avail. I'm at a loss. Please help me out
Heres my ajax code
$.ajax({
url: 'URL',
type: 'GET',
contentType: "application/json",
dataType: 'jsonp',
jsonp: 'jsoncallback',
success: function(response){
console.log("inside ajax");
$.each(response, function(i,item){
var category = "<div class='icon-text'><a class='ajaxify' href='pages/onlineRecipe.html' onclick='$(setOnlineID("+item.id+"))' >"
+"<p><img alt='Image-alt' width='64' class='wrap-around' id='img"+item.id+"' />"
+"<strong>"+item.title+"</strong>"
+"<br/>"+item.desc+"</p></a></div>";
$('#categories').append(category);
var img = "#img" + item.id;
$(img).attr('src', "data:image/png;base64,"+item.image);
//other bindings
App.ajaxLinkify($("a.ajaxify"));
App.addTouchEvents($(".page"));
});
},
error: function(xhs, status, error){
//output.text('Ha producido un error cargando el dato. Por favor, intèntalo de nuevo.');
console.log("Ajax not working");
}
});
My suggestion would be to check <access origin="http://www.example.com" /> in res/xml/config.xml (cordova 2.3)
Try adding this jQuery.support.cors = true;
oh and one other tip, just incase it's caching a previous bad call add this to your ajax
cache: false,
need to add this to corresponding php file: header("Access-Control-Allow-Origin: *");

phonegap jQuery .ajax cross domain requests work in browser, fail in Android SDK

I've been on this now for three days, and I've tried pretty much every piece of alternative code and fixes to no avail.
Here's the code, taken from bog-standard jQuery examples:
$.ajax({
url: "http://api.wunderground.com/api/4213a68e7f20c998/geolookup/conditions/forecast/q/Australia/Noarlunga.json",
dataType: "jsonp",
success: function(parsed_json) {
alert("YEP!");
var loc = parsed_json['response'];
var weather = "Location: " + parsed_json.location.city + "<br />";
weather += "Wind: " + parsed_json.current_observation.wind_dir + " ";
weather += parsed_json.current_observation.wind_mph + "-" + parsed_json.current_observation.wind_gust_mph + " knts";
$("#info").html(weather);
}
});
and here's some config that lots of people suggested ( which did nothing )
$( document ).bind( "mobileinit", function() {
// Make your jQuery Mobile framework configuration changes here!
$.mobile.allowCrossDomainPages = true;
$.mobile.ajaxEnabled = true;
$.mobile.pushStateEnabled = false;
$.mobile.allowCrossDomainPages = true;
});
In addition, I have:
added <uses-permission android:name="android.permission.INTERNET" /> to the AndroidManifest.xml file
tested the json request URL in the browser on the same target ( works fine )
tested the page in FireFox / Chrome ( works fine )
tried the app on my Galaxy s2 over 3G ( UI all works fine but ajax request STILL fails )
Note this isn't the complete code, but it's just sitting in a standard phonegap deviceready listener event function wrapped in a standard .ready() function.
The fact this fails on my phone AND the SDK would seem to indicate a phonegap / Eclipse issue, and not a connection / permission issue.
I am trying to deploy to an Android 2.3 AVD, using the Android SDK. I haven't tried deploying to an Android 4 AVD yet.
I'd love it if anyone knows what the problem is because I've run out of suggestions to try!
If precondition is that you could modify php code on server..
Try this so you could test either in local browser or on mobile WITHOUT JSONP
1.Follow instruction of jQueryMobile website, which explains well how to make it work with phonegap (http://jquerymobile.com/test/docs/pages/phonegap.html)
In your <script></script> area, add
$(document).on("mobileinit", function(){
//apply overrides here
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
your ajax could be
$.ajax({
type: "GET",
url: "http://xx.xx.xx.xx/xxx/xx.php"
}).done(function( msg ) {
alert(msg);
//refresh the content
$( '.ui-content' ).load( 'xx/xx.html', function () {$(this).trigger('create') });
});
2.Your php is something like this:
<?php
header('Access-Control-Allow-Origin: *');//for local browser test
$test='[{"name":"aa","address":"aa"}, {"name":"bb","address":"bb"}]';
echo $test;
?>
in
$( document ).bind( "mobileinit", function()
add
$.support.cors = true.
:)
I tried lots of combinations and the thing that finally worked was adding the following to my index.html. The key thing is making sure it's loaded before you load jquerymobile (if you're using that). It won't work if it is loaded anywhere after that.
<script type="text/javascript">
$(document).bind("mobileinit", function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
</script>

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