Reputation: 79
What's the easiest way to get a visitors city, state and country based on their IP address and fill it into a form field?
For example I have a basic form field:
<input type="text" name="city" value="*AUTOFILL CITY HERE*" />
Instead of having them fill this information in I'd like to just hide the form field and have it autofill based on their IP.
Upvotes: 1
Views: 6444
Reputation: 464
I found a solution for you which is in the form of html, javascript and jquery.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<h3>Client side IP geolocation using <a href="http://ipinfo.io">ipinfo.io</a></h3>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>
<input type="text" value="" id="city" />
<script type="text/javascript">
$.get("https://ipinfo.io", function (response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
$("#city").html(response.city);
document.getElementById('city').value = response.city;
}, "jsonp");
</script>
</body>
</html>
City is filled in automatically, and using the same process you can display the State, as well as the Country, of your visitors.
Upvotes: 3