IP Address Location : Javascript Examples

ipapi ~ ipapi.co
2 min readJun 25, 2019

This post will help you integrate an IP Geolocation service in your website — helping you find the location of your visitors, right from the browser in just a few lines of Javascript.

Every week we receive dozens of support requests of users asking for quick start examples of integrating IPAPI in their website with Javascript. We are delighted to address each one of those requests and we have compiled a list of different methods people use to access the API here, for a handy reference.

IP address location with plain JS:

Most modern browsers now support fetch() API — a JS interface that is a better alternative over XMLHttpRequest, and looks similar to jQuery.ajax(). Fetch returns a promise containing the response from which you can obtain the JSON body.

// 1 - fetch() : Newer methodfetch('https://ipapi.co/json/')
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
});
// 2 - XMLHttpRequest : Older methodvar req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', 'https://ipapi.co/json/', true);
req.onload = function() {
console.log(JSON.parse(req.responseText));
};
req.send(null);

Fork fetch() example on Repl.it
Fork XHR example on Repl.it

Repl.it : JSON IP Lookup with Fetch API

jQuery : If you are already using jQuery, there are a couple of ways to get the location:

// 1 - jQuery.get() : Complete JSON object
$.get('https://ipapi.co/json/', function(data) {
console.log(data)
})
// 2 - jQuery.getJSON() : Complete JSON object
$.getJSON('https://ipapi.co/json/', function(data) {
console.log(data)
})
// 3 - jQuery.get() : Specific field
$.get('https://ipapi.co/city/', function(data) {
console.log(data)
})
// 4 - jQuery.ajax()
$.ajax({
dataType: "json",
url: "https://ipapi.co/json/",
success: function(data){
console.log(data);
}
})
// 5 - JSONP (JSON with padding) example for older browsers
$.getJSON("https://ipapi.co/jsonp/?callback=?",function(json){
console.log(json);
});

// 6 - JSONP
: An elaborate example
function mycallback(json){
console.log(json);
}
$.ajax({
url: "https://ipapi.co/jsonp/",
dataType: "jsonp",
jsonpCallback: "mycallback"
});

The response in all the above examples (except when a specific field is requested) is a JSON object that looks like this (more details in our API documentation)

{ip: “8.8.8.8”, city: “Mountain View”, region: “California”, region_code: “CA”, country: “US”, …}

Note : IPAPI supports CORS (Cross-Origin Resource Sharing) & JSONP. , so you can make a call to our API endpoint from your website (domain) without being blocked by the same-origin policy restrictions in web browsers.

--

--

ipapi ~ ipapi.co

IP Lookup | IP Geolocation API | IP Address Locator by Kloudend, Inc. USA. Trusted by Fortune 500 !