3

Hi I found how to get client ip by answer here: Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

But I don't understand how to use it.

This is what I have:

var user;
if ($('#user-id').length) {
    user = $('#user-id').text();
} else {
    http://jsonip.appspot.com/?callback=getip
    function getip(json){
       user = json.ip;
    }
}

I don't understand how to include the url and how to use the getip function.

I need to set the user to the ip address in the else.

Thanks!

Community
  • 1
  • 1
JSNewbie
  • 335
  • 3
  • 5
  • 10
  • As Mohamed pointed out, this requires help from the server. If you tell us what backend framework/language are you using, you'd get more concrete answers. – Chubas Aug 22 '10 at 05:01

4 Answers4

5

Using jQuery, you could make a JSONP call:

$.getJSON('http://jsonip.appspot.com/?callback=?',
        function(data){
          alert(data.ip);
        });

Probably easier to understand - an alternative, without jQuery, would be:

<script type="text/javascript">
    function getip(data){
      alert(data.ip);
    }
</script>
<script type="text/javascript" src="http://jsonip.appspot.com/?callback=getip">
</script>

Note that when you include http://jsonip.appspot.com/?callback=getip as a script in your HTML you get valid JavaScript as response:

getip({"ip": "147.234.2.5", "address":"147.234.2.5"});

This line executes your function with the proper parameter. Note that the function's name is given to it by query string.

Kobi
  • 135,331
  • 41
  • 252
  • 292
0

You could use something like this:

<script type="text/javascript">
  var userip;
</script>
...
<script type="text/javascript" src="http://l2.io/ip.js?var=userip"</script>
...
<script type="text/javascript">
  document.write("Your IP is :", userip);
</script>

Here is the url of this library: http://l2.io/

Rishabh Malhotra
  • 269
  • 3
  • 13
0

You can only access your domain from JavaScript, you cannot do cross-domain communication with JavaScript unless you do the communication with iframes.

If you have a dynamic backend such as PHP, Java, Python, Ruby, CGI, etc you can easily fetch the IP address from the user visiting your page. Each language has their own mechanism.

Community
  • 1
  • 1
Mohamed Mansour
  • 39,445
  • 10
  • 116
  • 90
  • 2
    You can definitely fire crossdomain requests. Read on about the `Access-Control` response headers. – BalusC Aug 22 '10 at 05:06
  • Sorry, I forgot to add the link, here it is: [`Access-Control`](http://www.w3.org/TR/cors/). – BalusC Aug 22 '10 at 05:57
0

You've got a random, free-floating URL in your javascript syntax.

This is how to make remote JSON request with jquery.

http://api.jquery.com/jQuery.getJSON/

I would suggest you get more familiar with javascript in general.

Greg
  • 7,782
  • 7
  • 43
  • 69