I’m trying to figure out how to use IPinfo’s API to get geographic coordinates and other location information using jQuery.
- supportbot
I’m trying to figure out how to use IPinfo’s API to get geographic coordinates and other location information using jQuery.
- supportbot
First a warning. Never put your API Token/Access Key on the frontend!
Learn more here: https://ipinfo.io/faq/article/127-how-to-use-the-token-security-feature
You should always put your Token on the backend! IPinfo has a PHP module you can use very easily or you can use the API on the PHP backend. Pass your user IP address to your backend and process it there with your token and the API! Here is a guide on using IPinfo Geolocation API on PHP
Here is the code using JQuery that uses the token on the frontend anyway:
<script>
var ip = '188.124.3.1';
var token = 'INSERT_YOUR_TOKEN_HERE';
$.ajax({
url: 'https://ipinfo.io/' + ip + '?token=' + token ,
dataType: 'jsonp',
success: function (json) {
var city = json.city;
/ the API response uses the postal keyword
var postal = json.postal;
// the API response returns loc which combines both latitude and longitude
var latitude = json.loc.split(",")[0];
var longitude = json.loc.split(",")[1];
console.log(city + ' ' + postal + ' ' + latitude + ' ' + longitude);
console.log('success!');
//execute a second ajax function to insert the values into a database.
$.ajax({
type: "post",
url: "insert_geolocation.php",
data: {
'postal': postal,
'lat': latitude,
'lng': longitude
},
success: function (data) {
// it's successful, do nothing else.
// the code also reaches this stage, but the database gets a row with NULL and 0 as values...So the response from the API is returning undefined, for an unknown reason.
},
});
},
error: function (html, data) {
console.log('Error!');
console.log(data);
}
});
</script>