Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cordova jQuery AJAX call timing out after 30 seconds regardless of timeout setting

I'm trying to execute the following function on Android to sync with an IoT device I'm making:

function NewDeviceFetchDeviceID(){
    strURL = "https://192.168.x.x/.....";

    return $.ajax({
        url: strURL,
        type: 'GET',
        timeout: 90000
    });
}

The device takes some time to churn a response to the request (about 45-50 seconds) so I need the timeout to be slightly longer than 30s. The timeout seems to work on iOS - if I set it to 5 seconds it will do so, if I set it for 90 it will wait the whole time. For Android, it seems that this argument is ignored.

I tried adding the following into config.xml under <platform name="android"> with no luck:

<preference name="LoadUrlTimeoutValue" value="90000"/>

and I tried with a lowercase "L", still no luck:

<preference name="loadUrlTimeoutValue" value="90000"/>

How can I properly increase the timeout argument for AJAX requests in a Cordova Android app?


Update: I've changed the function, and I indeed get "Timed out!!!" as the response after exactly 30 seconds:

function TryXHR(){
    try{
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                alert("ready state = 4");
            }
        };

        strURL = "https://192.168.x.x/......";
        xhr.open("POST", strURL, true);
        xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
        xhr.timeout = 120000; // Set timeout to 120 seconds (120000 milliseconds)
        xhr.onload  = function () { alert(xhr.response); }
        xhr.ontimeout = function () { alert("Timed out!!!"); }
        xhr.onerror = function () { alert("Non-timeout error"); }
        xhr.send();
    }catch(err){
        alert("exception caught: "+err.message);
    }
}
like image 419
Lil' Bits Avatar asked Oct 16 '22 11:10

Lil' Bits


1 Answers

So after about a month of struggling with this, I ended up using the Cordova Advanced HTTP plugin: https://www.npmjs.com/package/cordova-plugin-advanced-http

Using the setRequestTimeout method, I was able to increase the HTTP request timeout to 120 seconds:

cordova.plugin.http.setRequestTimeout(120.0);

After rewriting my requests to utilize this plugin, my issues were solved for Android 9/10, and everything still worked as expected for iOS 12/13.

like image 101
Lil' Bits Avatar answered Oct 19 '22 02:10

Lil' Bits