Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  130] [ 4]  / answers: 1 / hits: 46130  / 8 Years ago, mon, march 14, 2016, 12:00:00

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.


More From » jquery

 Answers
29

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

[#62938] Saturday, March 12, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;