title: XMLHttpRequest connection check
body: <p>I am trying to write a streamlined version of a XMLHttpRequest demo script shown here:</p>
  
  <p><a href="http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first" rel="nofollow">http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first</a></p>
  
  <p>I'm only going to use this on iPad, so I don't have to check for older versions of IE, and so on. On button click, I want to check if the connection exists. Here's my entire html page, including JavaScript snippet:</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script&gt;
  var myURL = "http://www.google.com";
  
  function testConnection(url) {
      var xmlhttp;
  
      xmlhttp = new XMLHttpRequest();
  
      xmlhttp.onreadystatechange = function () {
          if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
              alert("Connected!");
          } else {
              alert("Not connected!");
          }
      }
      xmlhttp.open("GET", url, true);
      xmlhttp.send();
  }
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  
  &lt;button type="button" onclick="testConnection(myURL)"&gt;Test Connection&lt;/button&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>For some weird reason, even though I'm online, when I click the button, I get repeated "Not connected" alerts, and only after a while I get the "Connected" alert, followed by no alerts. </p>
  
  <p>Looks like I messed up, but I can't see where. What should I change to make it work? </p>