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
Related
Javascript code:
var googledocsurl = "https://docs.google.com/viewer?url=";
$.ajax({
url: window.localStorage.getItem('basePath') + 'pdf/GetPdfUrls',
type: "GET",
data: { id: window.localStorage.getItem('userid') },
dataType: "json",
beforeSend: function () { $.mobile.loading('show'); },
success: function (returnValue) {
for (var i = 0; i < returnValue.length; i++) {
$('#pdfList').append("<li><a onclick=\"window.open('" + googledocsurl + window.localStorage.getItem('basePath') + returnValue[i].pdfUri + "\', '_blank', 'location=yes')\">" + returnValue[i].PdfCreationDate + "</a></li>")
}
},
error: function () {
},
complete: function () { $.mobile.loading('hide'); },
})
if i try this ajax call on the emulator and ripply it works no problem but as so on as i try it on my android device it works like 1/50 times, it's kind of inconsistent and this makes it really hard to fix or understand
The error that i can see in Visual Studio
Failed to load resource: net::ERR_NAME_NOT_RESOLVED
GetPdfUrls(0,0)
and if i click "GetPdfUrls(0,0)" i can see the response and it's populated with data but for some reason this gives me and error but as far as i can see it's all right to me(especially sens it works 1 out of 50 times i try)
The response:
[{"pdfUri":"Image/GetPdf/8259ff54-6cd2-48dd-a0dc-d39b255e9bad","PdfCreationDate":"2014-12-08"},{"pdfUri":"Image/GetPdf/f05ff375-45e2-429b-a8fc-2c9d660df263","PdfCreationDate":"2014-12-08"},{"pdfUri":"Image/GetPdf/211feab8-9715-4942-bf8c-f7e95188c987","PdfCreationDate":"2014-12-08"},{"pdfUri":"Image/GetPdf/6ded622b-2d3e-4151-8be3-01070d1b9d69","PdfCreationDate":"2014-12-08"},{"pdfUri":"Image/GetPdf/f34adfa9-7bbf-4db9-b7ee-92fd619b0dc0","PdfCreationDate":"2014-12-08"},{"pdfUri":"Image/GetPdf/b6e5e56c-68d3-4662-a00e-b11dc09bfd9a","PdfCreationDate":"2014-12-08"},{"pdfUri":"Image/GetPdf/cc633e61-adcd-414d-bfc7-d09a30e05b01","PdfCreationDate":"2014-12-15"}]
if you need more info just ask and ill try my best to provide!
Thanks in advance for all the help
Well don't i feel stupid now...
Seams like the phone don't have any internet when it's not connected to a wifi network and it seams to loses the connection to the router at random and connect to another wifi network (with no internet connection) that have the same signal strength and then change back at random (guess it take the known network with the best signal strength).
I was lucky i watch the logcat log and saw this change happen other wise i would have been stuck for a while :/
Anyway thanks all for your help!
I'm using django v.1.6 and dajaxice v.0.6. I've run into a problem with ajax not functioning on some android devices running Chrome.
From what I understand, this is a caching problem. People using ajax on it's own seem to be getting round the problem by setting the cache to false within the ajax function. An example from here shows how you might normally go about this with ajax.
$.ajax({
url: "yoururl.html",
context: document.body,
cache : false,
data: {
username : $('#username').val(),
password : $('#password').val(),
},
success: function ( data ) {
// do something
}
});
And apparently that doesn't always work as in a reply to the previous code segment, someone has responded that after jQuery 1.7.1 you may need to add a timestamp like so:
$.ajax( { url: "someserver/somepath/blah" + "?_=" + jQuery.now(), type: "PUT", data: somedata});
Here is an example of the code I'm trying to get to work:
function refresh_word(){
Dajaxice.game.refreshWord(Dajax.process,{'game_id':{{game.id}},'player_id':{{player.id}}});
}
Like I said, this works on iPhones and desktop browsers but fails on some android devices.
I'm clutching at straws, I tried disabling the cache for the entire page but it still doesn't seem to work.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
Is there a way to do this with dajax?
Thanks in advance for any help!
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.
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.
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