Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get country code using javascript [duplicate]

I can't figure out how to get a country code from a visitor that goes to my webpage. I have seen plenty of other examples but none use plain Javascript. Here is my current code:

<!DOCTYPE html>
<html lang="en-US">
<head>
</head>
<body>
    <script type="text/javascript">
        var userip;
    </script>
    <script type="text/javascript" src="https://l2.io/ip.js?var=userip">       </script>

    <script type="text/javascript">
        document.write("IP: ", userip);

        $.get("http://ipinfo.io/"+userip.text(), function (response) {
            reg.text("country code here" + response.country);
        }, "jsonp");
    </script>
</body>
</html>

I get the user's IP addrress from a JSONP request to ipinfo.io using the $.get method of jQuery.

Unfortunately l2.io.js does not return anything other then the ip at this time.

If anyone can help or has any examples please link all related JavaScript libraries that will be needed. Thanks.

like image 748
702cs Avatar asked Mar 14 '16 22:03

702cs


2 Answers

According to the docs on the website, you should be able to retrieve the country code with ipinfo. try using $.getJSON instead of $.get

var country_code = null;
$.getJSON('http://ipinfo.io/' + userip, function(data){
    country_code = data.country;
    alert(country_code);
});
like image 188
Xposedbones Avatar answered Oct 18 '22 23:10

Xposedbones


I have used the below code using jQuery and its working fine for me. I am getting the country_code , country_name etc.,.

 jQuery(document).ready(function($) {
    jQuery.getScript('http://www.geoplugin.net/javascript.gp', function() 
    {
        var country = geoplugin_countryName();
        alert(country);
        var code = geoplugin_countryCode();
        alert(code);
        console.log("Your location is: " + country + ", " + zone + ", " + district);
    });
});

Note: Do remember to import the plugin script as below:

<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>

like image 28
Mehnaz Saheb Avatar answered Oct 18 '22 23:10

Mehnaz Saheb