$.ajax calls don't go through on android devices - android

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!

Related

"TypeError: Network request failed" (React Native) Android fetch fails to work with local backend

I am trying to fetch from my react native app using my local backend, and it keeps failing. The fetch doesn't even hit my backend, I made debug messages and tested on my browser to make sure the rest api worked. It works on iOS. I am also able to access other websites, so the internet works on the emulator.
UPDATE: After further debugging and trying other fetch requests, I have found a different error, maybe they are related?
error Could not open fetch.umd.js in the editor.
info When running on Windows, file names are checked against a whitelist to protect against remote code execution attacks. File names may consist only of alphanumeric characters (all languages), periods, dashes, slashes, and underscores.
I've already added "android:usesCleartextTraffic="true" in my AndroidManifest.xml. I have also tried upgrading my react native to version 63.4 but the problem persists.
It prints to console "[GET] http://127.0.0.1:8090/api/v1/user/check/email/test#gmail.com" but then the app gets
"TypeError: Network request failed"
immediately after.
When I try that URL in my browser, it properly prints
{"transok":"0","errno":"001003","errmsg":"","timestamp":"1612157175224","data":{}}
I've spent days in frustration on this, if anyone could lead me in the right direction I would be unimaginably greatful. Please let me know if any more information is needed, I will edit this question to provide the details
This is the code for the fetch which doesnt work:
const APP_SERVER_HOST = 'http://127.0.0.1:8090';
const API_BASE = APP_SERVER_HOST + '/api';
const API_VERSION = '/v1';
const API_HOST = API_BASE + API_VERSION;
isEmailExist(callback) {
var url = API_HOST + '/user/check/email/'+this.state.email;
var options = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
console.log('[GET] ' + url);
//url is http://127.0.0.1:8090/api/v1/user/check/email/test#gmail.com
//url should post {"transok":"0","errno":"001003","errmsg":"","timestamp":"1612157175224","data":{}}
fetch(url, options).then((response) => response.json())
.then((responseData) => {
var retCode = responseData.errno;
console.log('[RTN] ' + responseData);
console.log('[RTN] ' + JSON.stringify(responseData));
if(retCode == Env.dic.ERROR_EMAIL_NOT_REG) {
console.log('[RTN] error email not reg');
return callback(false);
} else if(retCode == Env.dic.ERROR_EMAIL_EXIST){
console.log('[RTN] error email exist');
return callback(true);
}
}).done();
}
127.0.0.1 represents the emulator's localhost address. If you want to hit your machine's localhost you'll have to replace it with 10.0.2.2.
See Android docs for more information on why this is the case.

Setting dajax cache false

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!

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

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