0

I can't find a way to use the value obtained from the JSON function from ipify.org.

I need to use this value in another function, not just write it in HTML like in the examples on ipify.org.

I'm trying to assign a value to the window variable, but it can also be done in another way. I am trying to use the "javascript" example on the site: https://www.ipify.org/

<script type="text/javascript">
    function getIP(json) {
        window.ipa = json.ip;
    }
    alert(window.ipa); //return "undefined"
</script>
<script type="text/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
nima
  • 7,796
  • 12
  • 36
  • 53
viliam
  • 1
  • 1
  • 1
    That is because you are accessing the value even before its defined, you have to wait until script loads the data in getIp function, so call another function from inside of getIp function or define a callback for it. – Osama Malik Oct 30 '22 at 10:10

1 Answers1

-1

You have to make the request to and capture the response from api.ipify.org in your script, there are many ways to do this, I used the old, native XMLHttpRequest API.

You also need to attach this function call to an event (I used "onload" bellow).

Example:

function xhrget(items, route, callback){
  const xhr = new XMLHttpRequest();
  xhr.open('GET', route);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.timeout = 1000;
  xhr.send(encodeURI(items));
  xhr.ontimeout = function(e){
    callback('404');
  };
  xhr.onreadystatechange = function () {
    if(xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr.responseText);
    }
    if(xhr.status >= 500 && xhr.status < 600){
      callback('An error occurred, please wait a bit and try again.');
    }
    if(xhr.status === 404) {
      callback('404');
    }
  };
}

function getIP() {
  xhrget(null, "https://api.ipify.org", (ip) => {
    console.log(ip);
    window.ipa = ip;
    alert(window.ipa); //return "undefined"  
  });
}

window.addEventListener('load', (event) => {
  getIP();
});
Tomás Metcalfe
  • 163
  • 1
  • 4