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.
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);
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With