Error: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I was trying to make an AJAX Post to another domain http://freegeoip.net/ to get Geo Location and therefore the browser would not allow me to proceed due to cross-domains. Cross domain means that if you are on domain A.com and would like to make a request to domain B.com, it does not allow the request to be made since the boundaries are set on the domain A.com by your browser. Script tags allow us to overcome this boundary however we still cannot read or do anything with the data returned.

Ajax Post:

$.ajax({

url: 'http://freegeoip.net/json/',
type: 'POST',
dataType: 'json',
success: function (data) {

var ip = data["ip"];
var country_name = data["country_name"];
var city_name = data["city"];

}

});

Error:

XMLHttpRequest cannot load http://freegeoip.net/json/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:4868‘ is therefore not allowed access.

Solution ( Very Easy!) :

JSONP is just like the normal JSON we are used to but it also passes an extra parameters with more of your pages details. When sending a request to another domain B.com with JSON, if the domain B.com has JSONP enabled, it will change the response in a way to be readable for us to handle. Therefore, all we need to do is change the dataType from “json” to “jsonp” as follows:

$.ajax({

url: 'http://freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function (data) {

var ip = data["ip"];
var country_name = data["country_name"];
var city_name = data["city"];

}

});

This worked perfectly for me, and I could successfully get the Client IP, Country and City.

PS: the above requires jQuery to function since we are using a jQuery Ajax Request.

Goodluck 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s