Home > Mobile >  How get data from API link
How get data from API link

Time:10-31

How I get data from API link

https://get.geojs.io/v1/ip/geo.js

I use the code bellow but not working. Please anyone talk what I wrong here?

`

<div id="divIDClass"></div>
<script>
$.ajax({
  url: 'https://get.geojs.io/v1/ip/geo.js',
  success: function(data){
    document.getElementById('divIDClass').innerHTML = data.country_code);
  }
})
</script>

`

Show undefined inner html

CodePudding user response:

The response is not a valid JSON structure. When checking the response from that endpoint, it returns a string in the format geoip({ /* data here */ })

If you check the website https://geojs.io, they show an example of how to use it. You need to create a function named geoip() that receives a JSON object. In that function, you will be able to handle the response. Then, you create a <script> tag and set the source to be that address you made a request to. When that script gets loaded, it calls your geoip() function.

Check the website to see how to use it.

If you still want to make requests yourself and want the country details in JSON format, you can use the endpoint https://get.geojs.io/v1/ip/country.json (see the doc)

Example:

$.ajax({
  url: 'https://get.geojs.io/v1/ip/country.json',
  success: (data, status, req) => {
    // print the data in the console as it comes, to check on the structure
    console.log(data);
    
    // add it to the DOM
    $('#response').html(`Country: ${data.name} (${data.country}/${data.country_3}), ip: ${data.ip},`);
  },
  error: (req, errorMessage) => console.error(errorMessage)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="response"></div>

CodePudding user response:

Well, as it is not a json, you shuld use the example from docs https://www.geojs.io/:

<script type="application/javascript">
    function geoip(json){
      var userip      = document.getElementById("user_ip");
      var countrycode = document.getElementById("user_countrycode");
      userip.textContent      = json.ip;
      countrycode.textContent = json.country_code;
    }
</script>
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>

If you still want to use ajax:

<script>
    $.ajax({
      url: 'https://get.geojs.io/v1/ip/geo.js',
      success: function(data){
data = JSON.parse(data.slice(6,-1));
        document.getElementById('divIDClass').innerHTML = data.country_code);
      }
    })
</script>
  • Related