0

I have a piece of JS code which uses a public API by ipify to access my/or clients' IP address. I was essentially wondering if I could somehow print the json.ip (IP address) to the console)? It seems fairly obvious but I can't make it work.

  <script type="application/javascript">
  function getIP(json) {
    dataLayer.push({"event":"ipEvent","ipAddress" : json.ip});  
  }
</script>

<script type="ap.....
T D
  • 11
  • 3
  • What happens when you say `console.log(json.ip)` inside that function? – Samathingamajig May 18 '22 at 14:34
  • the script doesn't get triggered – T D May 18 '22 at 14:35
  • 2
    So maybe the problem is that your `getIP()` function isn't called instead of a problem with `console.log()`? We can't really help you without a [mcve]. From what you show here, you just declare a function and that's it. There is no reason for it to be called. – Ivar May 18 '22 at 14:38
  • Edit: it actually does but I get an error 'getIP undefined' – T D May 18 '22 at 14:43
  • Make sure your scripts are in the correct order. You cannot call a function that hasn't been defined/loaded yet. – Reyno May 18 '22 at 14:45
  • @Reyno Any suggestions how I could resolve the loading problem, because it seems that the error 'getIP undefined' I get is because of that? – T D May 18 '22 at 14:46
  • As Ivar said you need to provide more details like how the `getIP` function is called. Without more info this question will turn into a guessing game which is not what SO is about. Please edit the question with more info so we can help you. – Reyno May 18 '22 at 14:48
  • The function gets called using Google Tag Manager every time a user lands on the page. Here is the complete code: – T D May 18 '22 at 14:51

1 Answers1

0
<!DOCTYPE html>
<html>

<head>
    <title>Getting Clients IP</title>
    <style>
    p,
    h1 {
        color: green;
    }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <script>
    /* Add "https://api.ipify.org?format=json" statement
            this will communicate with the ipify servers in
            order to retrieve the IP address $.getJSON will
            load JSON-encoded data from the server using a
            GET HTTP request */

    $.getJSON("https://api.ipify.org?format=json", function(data) {

        // Setting text of element P with id gfg
        $("#gfg").html(data.ip);
    })
    </script>
</head>

<body>
    <center>
        <h1>IP address!</h1>
        <h3>Public IP Address of user is:</h3>
        <p id="gfg"></p>
    </center>
</body>

</html>
Sujon Mir
  • 13
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 19 '22 at 02:02