0

I've got a small problem. Possibly only a small issue, but after a few hours of searching, I wasn't able to find and fix my mistake unfortunately. Please be beginner friendly, this is my first experience with Javascipt.

Can someone give me some pointers on how to fix the mistake I made?

I'm trying to integrade Javascript into my Website to load an JSON Object and display it using Javascript with the setAttribute function.

HTML Extract:

<html>
    <body>
        <input type="text" class="form-control" readonly="true" placeholder="IP" aria-label="IP" id="ip-display">
    </body>
</html>

Javascript:

    function showIP () {
      ipvalue = document.getElementById("ip-display");
      ipvalue.setAttribute("value", "ip");
    }
    
    async function fetchIP() {
      const response = await fetch ('https://api.ipify.org?format=json')
      const ip = await response.json();
    
      console.log(ip);
      showip(ip);
    }
    
    fetchIP();
0

1 Answer 1

2

ipvalue.setAttribute("value", "ip"); makes the IP a fixed string,you need to pass it as a variable

function showIP (ip) { // pass ip here
  ipvalue = document.getElementById("ip-display");
  ipvalue.setAttribute("value", ip);
}

async function fetchIP() {
  const response = await fetch ('https://api.ipify.org?format=json')
  
 /* code here needs to change accodring to your actural response data,
   so that we can get the ip correct*/
  const ip = await response.json().ip

  console.log(ip);
  showIP(ip);
}

fetchIP();
Sign up to request clarification or add additional context in comments.

5 Comments

I'm getting an Uncaught Reference Error: (Uncaught (in promise) ReferenceError: showip is not defined at fetchIP (test.js:11:3)). When I use const function, it says unexpected token 'function'
@Severus15 showIP not showip when you invoke it,function name is case sensitive
Ah damn. Thanks. :D Now it's displaying [object Object] instead of the IP. Do you know what I missed there?
@Severus15 your response it's json object,you need to get the ip from it
Wrap using JSON.parse on your [object Object] value and then you get the actual JSON data. @Severus15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.