My relevant code/settings
function
test(){
var
url =
"https://subdomain.mydomain.com/api/service"
$.support.cors =
true
;
$.mobile.allowCrossDomainPages =
true
;
$.ajax({
url: url,
dataType:
"JSON"
,
type:
"GET"
}).success(
function
(){
alert(
"success"
);
}).fail(
function
(){
alert(
"CORS error"
);
})
}
<
cordova
>
<
access
origin
=
"http://127.0.0.1*"
/>
<!-- allow local pages -->
<
access
origin
=
"*"
subdomains
=
"true"
/>
<
content
src
=
"index.html"
/>
<!-- All the other settings ...... -->
</
cordova
>
I am using:
- jquery 1.9.1
- jquery mobile 1.3.1
- cordova 3.5.0 (3.5.1 android)
I also have the corresponding CORS headers enabled in my server.
Any Ideas why this is not working?
19 Answers, 1 is accepted
When you are developing a Cordova powered hybrid app, you do not need to make CORS requests. Regular XHR requests will work without a problem. The reason for this is that a mobile app is executed from a file URI and does not comply to the cross origin policy. Mobile apps have an alternative to this policy which is called domain whitelisting. Telerik AppBuilder white lists all domains by default, so you can make requests freely.
Please, try to make the request without the CORS headers and see if this works for you. If this does not work for you, please elaborate more on what errors you are receiving. You can also open a support ticket and send us a sample project, so that we can investigate why the ajax requests are failing for you.
I am looking forward to your reply.
Regards,
Martin Yankov
Telerik
Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

did you found any workaround about this issue ?
i am facing same.
thanks in advance.
Please open a support ticket and provide a sample project where this is reproducible, so that we can investigate these issues.
Regards,
Martin Yankov
Telerik
Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

This was caused by having this line in the AndroidManifest.xml file
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="21"/>
Removing the android:targetSdkVersion="21" so it just read
<uses-sdk android:minSdkVersion="11" />
Then build again and all my Ajax issues went away.
Perhaps Telerik can shed some light on why this causes this.
Thanks
Removing the targetSdkVersion value automatically switches the SDK that is used when building to the minSdkVersion. Basically, what you say is that your app works with target sdk 11 which is Android 3.0.x and does not work with sdk 21 which is Android 5.0. The reason for this are the changes made in the Android 5.0 WebView behavior and namely the blocking of third party cookies. You can read about them here. Using cookies in hybrid mobile apps is not a best practice. The reason for this is that cookies are shared between all web views in all apps on the device. This can lead to mixing cookies between a browser (with the same domain as your ajax requests) and your app. Things can get messy. It is much more natural to use localStorage in mobile apps as a place to remember user auth.
Regarding Andy's problem below, this can be due to lack of an INTERNET permission of your app. If your app does not make ajax calls at all or they return a status code 0, go to your Project Properties -> Android -> Permissions and check if the INTERNET permission is turned on.
I hope this information helps.
Regards,
Martin Yankov
Telerik
Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

Thanks that explains it well, It does mean though to target sdk 21 then I would not only have to modify hybrid app but also the app I'm authenticating against. That's fine long term but like most things that's a staged process and it would be good in the meantime if appbuilder exposed the two methods setMixedContentMode and setAcceptThirdPartyCookies perhaps in the Android config that would allow this to work even when targeting new sdk versions while the developer plans to move over to the new standard and recommended practices.
Although I can see you guys seeing this as a bad thing as it does kind of promote bad practices if not used right but I thought I would throw it out there to see if it's something you guys could think about.
Thanks
Actually, Cordova has fixed this issue in the 3.7.0 release. Here are the release notes. AppBuilder supports Cordova 3.7. You can change it from your Projet Properties -> General -> Cordova Version. Try building your app with Cordova 3.7 and set the targetSdk to 21.
Let me know if your cookies work with this setup.
Regards,
Martin Yankov
Telerik
Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

I am using 3.7.0 Cordova version in my project and still had the issue. However looking at the Cordova version appbuilder offers in the drop down it looks like this 3.7.0 (Android 3.6.4, WP 3.8.0). So I guess that appbuilder only uses Cordova 3.7 for IOS and is yet to offer it for Android with the above fix you mention.
Thanks
I apologize I missed the fact that AppBuilder is building Android apps with Cordova 3.6.4. We have plans to update all platforms to the latest Cordova versions. This requires extensive testing and verification all systems work well with the newer versions and we are hoping to provide these new Cordova versions for all platforms with the next major AppBuilder release which is scheduled for the second part of April.
In the meantime, the workaround is to use targetSDK below 21 for Android.
Regards,
Martin Yankov
Telerik
Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

What is the solution here?
I have the request:
municipalities:
function
() {
var
opts = [];
$.ajax({
dataType:
"json"
,
type:
"GET"
,
async:
false
,
success:
function
(data){
opts = data;
},
error:
function
(xhr, ajaxOptions, thrownError) {
$(
"#dlog"
).html($(
"#dlog"
).html()+
"status: "
+xhr.status+
" msg: "
+thrownError.message);
}
});
return
opts;
},
I have "internet" set to "on", I verified that config.xml sets <allow origin="*" />.
The script https://my_domain.com/app/api/municipalities sets "Access-Control-Allow-Origin: *" and ""Access-Control-Allow-Methods: GET,POST"
When I run it, it just says "status: 0 msg: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://my_domain.com/app/api/municipalities'"
This is *so* frustrating. I tried removing android:targetSdkVersion="21" - but nothing...
I am pretty much dependent on ajax working :P


Such problems can be hard to detect and investigate and I am glad you were able to figure this out yourself.
Do not hesitate to ask should you encounter any other issues or questions.
Regards,
Martin Yankov
Telerik
Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

Hi Martin,
Unfortunately with the experimental Cordoba version 3.8.0 (for Android 3.7.1) the ajax-call still not working on a Android platform. The access setting in the config.xml ("*") is correct.
If I put the url hardcoded in the call then it works fine, otherwise when I use a variable the ajax-call returns a page-not-found (404-error). Debbuging the result I see that the url misses the domain name. That's why it comes up with an 404-error.
Putting the url hardcoded is not the solution for me.
Working and not working code snippets:
var
myurl =
"http://testdomain.com/page/test.asmx"
;
$.ajax({
type:
"POST"
,
url: myurl + "/Absences_Get",
/* And this doesn't work! */
I don't think the problem you are describing is connected to the Cordova or the platform. Most probably, it is a problem in your code. Is this your actual code in your app? Can you please open a support ticket and send us a sample project where we can reproduce this?
Thanks in advance for your cooperation.
Regards,
Martin Yankov
Telerik
Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

after countless hours of downgrading/upgrading plugins, cordova, endless searching on stackoverflow, attempting all alleged solutions dealing with cordova-plugin-whitelist... the solution was ultimately to comment out my android-targetSdkVersion of 23, leaving only android-minSdkVersion of 19.
THANK YOU for suggesting this.

Hi !
I have the same trouble.
I make an app. When I test the app in the emulator Intel XDK, the app work; if use the app directly from the Explorer, the app work; but when i build the apk from the site build.phonegap and i installed, the app don't work.
I send the Project in zip format
Thank you for your help

THis is my code php
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
//header('Access-Control-Allow-Origin: *');
//header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
//header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// Incluye el archivo de Conexion
require("conexion.php");
// Variables para acceso
$sUsuarioIde="";
$sUsuarioCve="";
// Obtiene Usuario y Clave del POST
//echo "Obteniendo parámetros de Acceso ...<br>";
if (isset($_POST['UsuarioIde']))
$sUsuarioIde = $_POST['UsuarioIde'];
if (isset($_POST['UsuarioCve']))
$sUsuarioCve = $_POST['UsuarioCve'];
// Preparamos el Query de Consulta a Usuarios
$Query = " SELECT * FROM usuarios ";
$Query .= " WHERE UsuarioIde='".$sUsuarioIde."'";
$Query .= " AND UsuarioCve='".$sUsuarioCve."'";
// Ejecuta Query y obtiene Registros
//echo "Ejecutando Consulta de Acceso ...<br>";
$Registros = $conexion->query($Query);
if (!$Registros)
{
die ("Error en Consulta :<br>".$conexion->error);
}
// Verifica si hubo resultados
if ($Registros->num_rows<=0)
{
echo "Error en Usuario y Clave <br>";
}
else
{
// Obtiene el Registro
$Row = $Registros->fetch_assoc();
$result[] = array('ide' => $Row["UsuarioIde"],'nom' => $Row["UsuarioNom"],'tip' => $Row["UsuarioTip"]);
echo json_encode($result);
//echo ($result);
}
and this is my code JS
$.ajax(
{
data:parametros, // Parametros para ajax
url :"http://"+sHost+"/scm/www/php/ajaxAcceso.php",
type:'post', // Método de transferencia
crossDomain: true,
async: true,
headers: {
'Access-Control-Allow-Origin': '*.*',
'connect-src': 'https://10.0.0.25'
},
beforeSend: function() // Se ejecuta antes de
{
$("#idResultado").html("Accediendo al Servidor:"+sHost);
},
success: function(respuesta)
{
//alert(respuesta);
$("#idResultado").html(respuesta);
var sResultado = respuesta;
var json = JSON.parse(respuesta);
$("#idResultado").html(json[0].nom);
if (sResultado.indexOf("Error")<0)
window.location.href="principal.html?"+json[0].tip+
"="+json[0].ide+"."+json[0].nom+":"+sHost;
}
},
"json")
.fail(function()
{
alert("Error Inesperado en el acceso al Sistema");
});
Thank you
It is not sure what may be not working with the request (error is returned, the request is not executed, etc.) but this may be a possible cause and solution - AJAX jQuery Requests Do Not Work on Android
Note that this article addresses the problem on apps built in Telerik Platform but should be applicable for other cases for apps built on top of Apache Cordova.
I hope this helps.
Regards,
Anton Dobrev
Progress Telerik
Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.