How to Convert Maxmind Geoip1 javascript script to Geoip2

1.1k views Asked by At

Using the first Geoip I was using a simple Javascript code (as seen below), but I've been trying all day to figure out what I need to do to have the script recognise the country code for Maxmind Javascript Geoip2.

The Original GEOip code

<script type="text/javascript">
var user_country = geoip_country_code();

if(user_country == "US")
document.write(hockeyAds[4]);
else
document.write(hockeyAds[5]);
</script>

What I have in the new header

  <script type="text/javascript" src="//j.maxmind.com/js/apis/geoip2/v2.0/geoip2.js"></script>

The latest code that I have attempted to use.

<script type="text/javascript">
var user_country = geoip2.cityISPOrg.country.iso_code();
if(user_country == "US")
document.write(hockeyAds[4]);
else
document.write(hockeyAds[5]);
</script>

Below on the same page I have tried this script that someone made and I was able to get it to type out the correct country code. So I am convinced that it is a problem with the above javascript code.

<script>
geoip2.cityISPOrg(function (response) {
    $("#usercountry").html(response.country.iso_code);
});
</script>
<p>
    <span id="usercountry"></span>
</p>

Not really all the great with understanding Javascript. Thanks

1

There are 1 answers

1
jonahb On BEST ANSWER

You need to pass success and error callbacks to the geoip2 methods. Try this:

geoip2.country(
    function (response) {
        if (response.country.iso_code === "US") {
            document.write(hockeyAds[4]);
        } else {
            document.write(hockeyAds[5]);
        }
    },
    function (error) {
        // handle error
    }
);

Also, this tutorial might help you understand the API: http://dev.maxmind.com/geoip/geoip2/javascript/tutorial/