Search code examples
javascriptjqueryapigetjson

getJSON function get data from url on localhost only


I use below function to get the Continent Code from the api which works fine on localhost but fail in live environment which is website

$.getJSON('//www.geoplugin.net/json.gp?jsoncallback=?', function (data) {
  // console.log(JSON.stringify(data, null, 2));
  console.log(JSON.stringify(data.geoplugin_continentCode));
});

Warning which i see in Console is

Loading failed for the with source “https://www.geoplugin.net/json.gp?jsoncallback=jQuery16407901144106031991_1537089290623&_=1537089292750”.

I am not sure why it fails on website https://www.example.com

could SSL version some problem as i am not sure as i tried it on fiddle & it works fine http://jsfiddle.net/om8ahkp3/

UPDATE

Since problem was due to crossdomain issue which as this api used a different url for ssl version. i was not able to use this ssl version as it was not free.

So ended up using another api which had free option also limited to 50k request on monthly basis.

$.ajax({
                url: 'https://api.ipgeolocation.io/ipgeo?fields=is_eu& excludes=ip&apiKey=YOURKEY',
                dataType: 'json',
                success: function (json) {
                    console.log("json.is_eu " + json.is_eu);
                }
            });

Solution

  • What is the whole problem? You want to access to a third site (crossDomain). So, That site decides that you can access to it, or not. When a site provides a service (similar geo service that you have used it), it determines which part of it's services are free.

    In your case, if your source site's protocol is http (like as localhost) and dest site (service provider site) is http too, you can access to this geo service with your above code (because this third site allows this now). But if you want to access to this service from a https site (I think you are trying this now) the geoPlugin don't allow you easily or free!

    In this cases, the destination sites, provide another urls and define user levels (to getting money for special services.).

    In act, if your dest site was for yourself too(which it is not in this case), you could add needed access to specific referer sites, but now...

    I look at its site to be sure. You must use this url in this case:

    https://ssl.geoplugin.net/json.gp?k=yourAPICode

    But this is not all of things! What is k in above url? This site writes: "For SSL access, an API Key is required to offset certificate prices and costs €12 per year."

    I don't know, but if you need it, you should search for free plugins (if exists) or buy it.