This is a migrated thread and some comments may be shown as answers.

$.ajax Not working on android devices

19 Answers 2909 Views
Android Devices
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Josef
Top achievements
Rank 1
Josef asked on 30 Sep 2014, 05:48 PM
I have an application, that needs to access an api. All ajax requests in android devices are not working. I have tested the app from AppBuilder companion app.

My relevant code/settings

function test(){
    $.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

Sort by
0
Martin Yankov
Telerik team
answered on 01 Oct 2014, 10:53 AM
Hi Josef,

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.

 
0
Inx
Top achievements
Rank 1
answered on 06 Feb 2015, 05:25 AM
hello josef,

did you found any workaround about this issue ?

i am facing same.

thanks in advance.
0
Martin Yankov
Telerik team
answered on 10 Feb 2015, 12:15 PM
Hi,

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.

 
0
Paul
Top achievements
Rank 1
answered on 11 Mar 2015, 08:01 PM
I had a similar issue where auth cookies were not being passed up in ajax requests.

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
0
Martin Yankov
Telerik team
answered on 16 Mar 2015, 09:27 AM
Hi Paul,

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.

 
0
Paul
Top achievements
Rank 1
answered on 16 Mar 2015, 01:47 PM
Hi Martin,
               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
0
Martin Yankov
Telerik team
answered on 19 Mar 2015, 09:32 AM
Hello Paul,

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.

 
0
Paul
Top achievements
Rank 1
answered on 19 Mar 2015, 09:58 AM
Hi Martin,
               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
0
Martin Yankov
Telerik team
answered on 23 Mar 2015, 11:42 AM
Hi Paul,

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.

 
0
Lars Golovitcher
Top achievements
Rank 1
answered on 17 Apr 2015, 06:03 PM

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

0
Lars Golovitcher
Top achievements
Rank 1
answered on 17 Apr 2015, 06:18 PM
On a hunch, I decided to test it without SSL - then it worked. How do I get it to work via HTTPS? It is a valid certificate!
0
Lars Golovitcher
Top achievements
Rank 1
answered on 17 Apr 2015, 06:44 PM
Ok, it turned out to be the SSL-certificate that wasn't properly installed (problem with intermediate certificates) - once I fixed that, everything works as expected.
0
Martin Yankov
Telerik team
answered on 20 Apr 2015, 08:08 AM
Hello,

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.

 
0
Gonen
Top achievements
Rank 1
answered on 27 May 2015, 08:30 AM

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:

$.ajax({
    type: "POST",
    url: "http://testdomain.com/page/test.asmx/Absences_Get",   /* This works! */

$.ajax({
    type: "POST",
    url: myurl + "/Absences_Get",  /* And this doesn't work! */

0
Martin Yankov
Telerik team
answered on 01 Jun 2015, 08:31 AM
Hi,

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.

 
0
kris
Top achievements
Rank 1
answered on 06 Jul 2016, 12:56 AM

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.

0
Juan
Top achievements
Rank 1
answered on 19 Jul 2017, 08:10 PM

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

 

0
Juan
Top achievements
Rank 1
answered on 19 Jul 2017, 08:12 PM

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

0
Anton Dobrev
Telerik team
answered on 24 Jul 2017, 09:48 AM
@Juan

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.

 
Tags
Android Devices
Asked by
Josef
Top achievements
Rank 1
Answers by
Martin Yankov
Telerik team
Inx
Top achievements
Rank 1
Paul
Top achievements
Rank 1
Lars Golovitcher
Top achievements
Rank 1
Gonen
Top achievements
Rank 1
kris
Top achievements
Rank 1
Juan
Top achievements
Rank 1
Anton Dobrev
Telerik team
Share this question
or