views:

21

answers:

2

Hi, I have some code that if I'm at home; it will display at popup saying that if you are at home. If you are not at home it will display a popup saying you are not at home. As the script is located on a server to give an IP address, how can I get it to say if you are not connected to the internet, as it will fail to load so I would have though that ip!="" would work but doesn't what have I done wrong? Thanks

<script type="application/javascript">
    function getip(json)
    {
        ip=json.ip
        if(ip!="")
        {
            if(ip=="123.123.123.123")
            {
                alert("You are at home");
            }
            else
            {
                alert("you are not at home");
            }
        }
        else
        {
            alert("You are not connected to the internet");
        }
    }
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"&gt;
</script>
+1  A: 

The way JSONP works is to call that method with the response, your server response from http://jsonip.appspot.com/?callback=getip looks something like this:

getip({ "ip": "123.123.123.123", "addres": "123.123.123.123" });

But when you're not connected that script include just errors, and the method isn't ever called, that's the issue. Your if check, and the entire getip() method, isn't ever hit. You could do a very simple timeout, like this:

var timer = setTimeout(function() { 
  alert("You are not connected to the internet");
}, 10000); //10 seconds
function getip(json){
  clearTimeout(timer);
  if(json.ip == "123.123.123.123") {
    alert("You are at home");
  } else {
    alert("you are not at home");
  }
}
Nick Craver
A: 

Your problem is that if the JSONP fails to load, the whole function won't be called at all.

In theory, there is the onerror event for the <script> element that you could use, but according to this question, it doesn't work reliably in IE.

However, that question shows a workaround that might work for you, too: Embedding a script that sets a variable, and checking for that variable afterwards. That would be an option if you control the remote app that you are calling.

If that is not a possibility, I think the only thing you can do is have the callback function set a flag like json_loaded = true; and use a setTimeout to check for that flag after a few seconds. If the flag is not set, the script failed to load and you need to act accordingly.

Pekka