0

I am having some trouble getting IP information to fill a hidden Form field.

So far I used a free service ipinfo.io but because I am getting way too many responses per day, this free website is not going to be enough. Therefore I will have to buy a better service.

This is the code i used till today:

<script type="text/javascript">

$.get("https://ipinfo.io", function (response) {
    $("#IPnaslov").html("IP: " + response.ip);
    $("#address").html("Location: " + response.city + ", " + response.region);
    $("#details").html(JSON.stringify(response, null, 4));
    $("#city").html(response.city);
    document.getElementById('ip').value = response.ip;
}, "jsonp");
</script>

<form>
<input name="IPnaslov" type="hidden" id='ip'type="hidden">
  <br><button type="submit" class="btn btn-outline-danger" name="submitted" value="true">Submit</button>
</form>

There ar emany IP service on the market and i can't figure out which one to use. I tried https://smartip.io/ because it has a free registration for up to 125000 requests.

Is there a way I can use their service similar to the way I used ipinfo.io?

Thank you again for the help in advance.

IceBurger
  • 155
  • 1
  • 8
jurekutos
  • 5
  • 2

1 Answers1

0

First, you should not call the API when the visitor is not human. That would save some requests.

if (navigator.userAgent.match(/bot|spider/i)) {
    // It is a bot, probably keep it going to crawl your site
} else {
    // It's not a bot, hit the API:
    $.get("https://api.smartip.io/[client_ip]?api_key=[YOUR_API_KEY]", function(response) {
        console.log("response");
    });
}

Anyway, that service need you to pass the IP. You can not get the IP with just javascript. You have to do it server-side.

You should, instead, use any other from this answer.

Personally, I use geoPlugin.

This should work for you:

$.getJSON('http://www.geoplugin.net/json.gp?jsoncallback=?', function(data) {
  $("#IPnaslov").html("IP: " + data.geoplugin_request);
    $("#address").html("Location: " + data.geoplugin_city + ", " + data.geoplugin_region);
    $("#details").html(JSON.stringify(data, null, 4));
    $("#city").html(data.geoplugin_city);
    document.getElementById('ip').value = data.geoplugin_request;
});
Hache_raw
  • 471
  • 3
  • 10