So i'd like to have a text saying [Location] which will be shown and changed based on the viewer's location/ip. I tried to follow this video here https://www.youtube.com/watch?v=1KiGKd2XXL4 but i didn't manage to make it to work. I registered on 2 websites to get an API key which i placed it in the script and yet it didn't work out. What I tried in a nutshell is

<script>
    $('document').ready(function() {
        $.ajax({
          url: "https://api.snoopi.io/check?apikey=MY API KEY",
          dataType: "jsonp",
          jsonpCallback: "unBounce"
        });
    }); // Ready
function unBounce(json){
   $('#location').html(json.City + ", " + json.State);
}
</script>

Followed by

<span id="location"></span>

What happens when you just go to the URL https://api.snoopi.io/check?apikey=MY API KEY ? Does the API correctly provide your location in JSON format?

Yes it does! :)

Can you please share a public link to a URL where you are testing/using it so that I can investigate further?

I'm working on spaces.w3schools .com

What I mean is, can you please provide the URL on spaces.w3schools.com, so that I can see if maybe it's a CORS issue that is causing the problem. (That's my best guess as to what the problem is, but if I can check out the URL, I can investigate further.)

I signed up and tested the Snoopi code, and the following works. JQuery is needed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Location</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1>Your Location</h1>
    <div id="location">Loading...</div>

    <script>
        $(document).ready(function() {
            $.ajax({
                url: "https://api.snoopi.io/check?apikey=a11...0b",
                dataType: "jsonp",
                jsonpCallback: "unBounce"
            });
        }); // Ready

        function unBounce(json){
            $('#location').html(json.City + ", " + json.State);
        }
    </script>
</body>
</html>

Unfortunately a bug was preventing alexxx1 from posting. He messaged me:

Btw the location js is resolved. I needed to add fetch()

I'm honestly confused where he needed to add fetch()?

Maybe something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Location</title>
</head>
<body>
    <h1>Your Location</h1>
    <div id="location">Loading...</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            fetch('https://api.snoopi.io/check?apikey=a11...700b')
                .then(response => response.json())
                .then(json => {
                    document.getElementById('location').innerHTML = json.City + ", " + json.State;
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('location').innerHTML = 'Failed to retrieve location';
                });
        });
    </script>
</body>
</html>

My first thought was the function name was the same as the keyword fetch.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Location</title>
</head>
<body>
    <h1>Your Location</h1>
    <div id="location">Loading...</div>

    <script>
        function fetch() {
            const script = document.createElement('script');
            script.src = 'https://api.snoopi.io/check?apikey=a11...00b&callback=unBounce';
            document.body.appendChild(script);
        }

        function unBounce(json) {
            document.getElementById('location').innerHTML = json.City + ", " + json.State;
        }

        // Calls the function to get the location
        document.addEventListener('DOMContentLoaded', fetch);
    </script>
</body>
</html>

Hope this helps.

That's only if he chooses not to use jQuery.

I see.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Location</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1>Your Location</h1>
    <div id="location">Loading...</div>

    <script>
        $(document).ready(function() {
            fetch('https://api.snoopi.io/check?apikey=a11...00b')
                .then(response => response.json())
                .then(json => {
                    $('#location').html(`${json.City}, ${json.State}`);
                })
                .catch(error => {
                    console.error('Error:', error);
                    $('#location').html('Failed to retrieve location');
                });
        });
    </script>
</body>
</html>

This should do the trick.

That seems like a worse solution. There’s no performance nor complexity advantage to using jQuery. Your previous example was much better.

Just my guess, since you said they used fetch(). Without seeing all the code, not much more I can do here... maybe... especially if the first example worked fine, without adding some fetch().

We don't know the whole scope here. Maybe he wants to be redundant? What happens if the script source fails, yet he has the built-in fetch() API, which doesn't need additional libraries? Another solution.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Location</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        // Fallback if jQuery fails to load from primary CDN
        window.jQuery || document.write('<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"><\/script>');
        // Fallback if jQuery fails to load from secondary CDN
        window.jQuery || document.write('<script src="jquery.min.js"><\/script>');
    </script>
</head>
<body>
    <h1>Your Location</h1>
    <div id="location">Loading...</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            if (window.jQuery) {
                // jQuery is loaded
                $.ajax({
                    url: "https://api.snoopi.io/check?apikey=a11...00b",
                    dataType: "jsonp",
                    jsonpCallback: "unBounce"
                });
            } else {
                // jQuery failed to load, use fetch as a backup
                fetch('https://api.snoopi.io/check?apikey=a11...00b')
                    .then(response => response.json())
                    .then(json => {
                        document.getElementById('location').innerHTML = json.City + ", " + json.State;
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        document.getElementById('location').innerHTML = 'Failed to retrieve location';
                    });
            }
        });

        function unBounce(json) {
            $('#location').html(json.City + ", " + json.State);
        }
    </script>
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.