I am using jQuery to get visitor's location via their IP address. There's a great service for this called freeGeoIP. All I need to do is tack 'json' or 'xml' at the end of their URL, then add the IP address, and it will return the required data.
When I do this manually in my browser, it works: I get a tiny document to download. When I do a $.ajax or $.getJSON request from the browser, it answers with a '200 OK' header and the metadata below. But no actual data comes in. What's going on?
EDIT: I've added the javascript/jQuery code:
function openForm(event,ui){
var _this = $(this);
//Get details on the user's IP
var myIP = $('#yourIP').attr('ip');alert(myIP);
var url = 'http://freegeoip.appspot.com/json/' + myIP;
$.ajax({
url: url,
dataType: 'json',
contentType: 'text/json',
timeout: 10000,
complete: function(ip){
alert('Success Ajax!');
//URL returns status,ip,countrycode,countryname,regioncode,regionname,city,zipcode,latitude,longitude
$('#yourIP').text(ip.city + ", " + ip.countryname + " at " + ip.latitude + " latitude.");
$('#yourIP').attr({'city': ip.city,'country': ip.countryname});
}
});
RESPONSE HEADERS
Cache-Control no-cache
Content-Type text/json
Expires Fri, 01 Jan 1990 00:00:00 GMT
Content-Encoding gzip
Date Fri, 17 Dec 2010 15:26:48 GMT
Server Google Frontend
Content-Length 156
REQUEST HEADERS
Host freegeoip.appspot.com
User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.1; nl; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)
Accept application/json, text/javascript, */*; q=0.01
Accept-Language nl,en-us;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Content-Type text/json
Referer http://www.freshbase.nl/permaculture/index.php
Origin http://www.freshbase.nl
That's because you're running afoul of the cross-domain request limitation of the XMLHttpRequest object used in jQuery's AJAX features. Some browsers throw an empty 200 response when that happens (which is confusing).
You need to either use a service that supports JSONP, to circumvent the cross-domain issue, or use a server-side proxy on the same domain to act as a local intermediary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With