user1691389
user1691389

Reputation: 453

make jquery snippet conditional to an IP

Is there a way to make this snippet fire off ONLY if my own IP is visiting the site?

        $('#preloader').delay(5555).fadeOut(1234,function(){  
           $(this).remove();
        });

Something like (pseudo-code): "IF ip is NOT 127.0.0.1, do nothing."

(I'm open to a PHP solution if that would be easier.)

Thanks!

Upvotes: 1

Views: 245

Answers (3)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You'll get the clientIP using both javascript and jquery. You can, relaying it via server side with JSONP

And while googling to find one, found it here on SO http://stackoverflow.com/questions/102605/can-i-lookup-the-ip-address-of-a-hostname-from-javascript

<script type="application/javascript">
    function getip(json){
      alert(json.ip); // alerts the ip address
    }
</script>

<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>

also,jQuery can handle JSONP, just pass an url formatted with the callback=? paramtere to the $.getJSON method, for example:

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

This example is of a really simple JSONP service implemented on Google App Engine, you can see more details here.

Check the source of the service, is a small Python script, it can be implemented on any server-side language.

If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.

Run the above snippet here.

Upvotes: 0

Viacheslav Kondratiuk
Viacheslav Kondratiuk

Reputation: 8879

You can make this condition at PHP to show this part of code or not.

<? if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1'): ?>
    $('#preloader').delay(5555).fadeOut(1234,function(){  
        $(this).remove();
    });
<? endif; ?>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337580

Javascript cannot get the IP of the visitor, so a sever-side solution is the only one possible. Try this:

<?php if ($_SERVER['REMOTE_ADDR'] == '1.1.1.1') { // your IP instead of 1.1.1.1 ?>
    $('#preloader').delay(5555).fadeOut(1234,function(){  
        $(this).remove();
    });
<? } ?>

Upvotes: 3

Related Questions