Home » Android » Javascript not working on mobile (Android) but fine on desktop-Exceptionshub

Javascript not working on mobile (Android) but fine on desktop-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment


I’ve searched the archives but not found anything specific to my query.

In JavaScript I have a function with a callback function that fires a request at a postcode API to get coordinates for a postcode.

const getPostCodeLatLng = (strPostCode, callback) => {
    alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
    const request = new XMLHttpRequest();
    request.addEventListener('readystatechange', () => {
        if(request.readyState == 4){
            const jsnPostCode=JSON.parse(request.responseText);
    request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);


getPostCodeLatLng(strInputFieldValue, (jsnPostCode) => { // use the function to get data about the postcode and callback to this function
                alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
                let strPostCodeLatLng = "LatLng(" + jsnPostCode.data.latitude + ", "
                + jsnPostCode.data.longitude + ")";
                objDisplayFindCons.value=`Postcode: ${strInputFieldValue}`;}
            else objDisplayFindCons.value=`No match found for Postcode: ${strInputFieldValue}`;})

The functions work fine on a desktop but didn’t work on either a Samsung phone nor tablet. I’m using Chrome on all devices.

The second section of code is part of a larger section that responds to an event where data is entered into a text box, validated as a possible postcode (using regex) and then requested as per the first function. The JSON text response is then parsed and checked to see if a match was found (the server returns valid JSON for unfound postcodes).
I am clear that it all works fine until it encounters the function call getPostCodeLatLng() where it never runs either of the alert("used API") statements on mobile.

I am new to JavaScript and finding coding callback functions and events challenging but I can’t see any obvious bugs/reasons for this to fail on mobiles.

Are there known problems or limitations to what I’m doing?

Is there a way to workaround this or debug it effectively on mobile?

Please help!



How to&Answers:

So I tried various things and found the issue to be with using a http request.

Apparently from now on all requests from a Chrome browser on Android need to be https.

So changing request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
to request.open('GET', 'https://api.getthedata.com/postcode/' + strPostCode); fixed the problem straightaway.

Here is an article mentioning the change:-

You live and learn…