How to get client country of your visitor by Javascript


Method 1: use https://get.geojs.io/v1/ip/geo.js (with jQuery)

var button = $("button")

$.ajax({
  url: 'https://get.geojs.io/v1/ip/geo.js',
  success: function(data){
  	button.html(data.match(/"country":"([^"]+)"/)[1])
  }
})

To get country code:

var button = $("button")

$.ajax({
  url: 'https://get.geojs.io/v1/ip/geo.js',
  success: function(data){
  	button.html(data.match(/"country_code":"([^"]+)"/)[1])
  }
})

Online demo: https://jsfiddle.net/sans_amour/r49v5w60/

Method 2: use https://get.geojs.io/v1/ip/geo.js

<div id="banner-message">
  <p>Your country</p>
  <button></button>
</div>
<script>
function geoip(data){
  document.getElementsByTagName('button')[0].innerHTML=data.country
}
</script>
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>

To get country code:

<div id="banner-message">
  <p>Your country</p>
  <button></button>
</div>
<script>
function geoip(data){
  document.getElementsByTagName('button')[0].innerHTML=data.country_code
}
</script>
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>

Online demo: https://jsfiddle.net/sans_amour/mps5y4j7/

Method 3: with http only, use http://ip-api.com/json (with jQuery)

var button = $("button")

$.ajax({
  url: 'http://ip-api.com/json',
  success: function(data){
  	button.html(data.country)
  }
})

To get country code:

var button = $("button")

$.ajax({
  url: 'http://ip-api.com/json',
  success: function(data){
  	button.html(data.countryCode)
  }
})

Online demo: http://jsfiddle.net/sans_amour/9zqpx1by/

Method 4: use Cloudflare and jQuery (country code only)

Cloudflare provide a url like: https://cloudflare.com/cdn-cgi/trace

For website using Cloudflare DNS, you can use your own domain: https://yourdomain.com/cdn-cgi/trace

var button = $("button")

$.ajax({
  url: 'https://cloudflare.com/cdn-cgi/trace',
  success: function(data){
  	button.html(data.match(/loc=(.+)/)[1])
  }
})

Online demo: https://jsfiddle.net/sans_amour/cdLxaqp8/

Leave a Reply