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);
});