How to get JSON data from http://ipinfo.io/json : Works on browser but not via $.ajax()

If I load http://ipinfo.io/json on a web browser I can see a JSON encoded object that looks like

{
“ip”: my ip,
“hostname”: my hostname,
“city”: my city,
“region”: my state,
“country”: my country,
“loc”: my coordinates,
“org”: my provider
}

and the info looks correct.

But I seem unable to get this via a JQuery’s ajax request no matter what I do.

I have succesfully used $.ajax() before, but don’t know what is going on here. The success callback does not get executed.

Here’s a function that works for another URL, but not for http://ipinfo.io/json

function getStuff(targetURL){
    $.ajax({
        type: 'GET',
        url: targetURL,
        cache: false,
        success: function(data){
            console.log("ajax is working!!");
        }

    })
}

What is it that I don’t get?

@fabricioch The code looks fine to me, did you check the console for any errors? I suspect targetURL haven’t been defined ?

the API request to the API for targetURL
e.g.
var **targetURL** = "make-request-to-API-here";

    function getStuff(targetURL){
        $.ajax({
            type: 'GET',
            url: targetURL,
            cache: false,
            success: function(data){
                console.log("ajax is working!!");
            }

        })
    }

Or:
–syntax errors
–Did you call the function? getStuff(targetURL);
– the function has been called out of its scope.
I’m just talking based on similar experience.

I was about to post a reply, but realized it is working now.

I could swear it wasn’t working for the URL in the OP when I created the thread but now it is, even though I have not changed a thing in the code.

Ah okay, maybe the error was on codepen side or wherever you was hosting the project. Glad it’s working now :slight_smile:

I suggest giving a look at Ipregistry (https://ipregistry.co) for a fast, reliable and inexpensive alternative to ipinfo.io:

https://api.ipregistry.co/?key=tryout&pretty=true

Here is an example using vanilla JavaScript:

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (request.readyState === 4 && request.status === 200) {
        var json = JSON.parse(request.responseText);
        console.log('Your country is ' + json['location']['country']['name']);
    }
};
request.open('GET', 'https://api.ipregistry.co/?key=YOUR_API_KEY', true);
request.send(null);