Sunday, November 11, 2007

Ajax Callback function not getting called

In a HTML page I was using a global Javascript request object.

<script type="text/javascript">
var request = null;
try {
  request = new XMLHttpRequest();
} catch (trymicrosoft) {
  try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      request = null;
    }
  }
}
...
</script>

The first time I executed my Ajax Javascript to issue a request to the server, the callback function worked ok and callback function was called. Each subsequent request hit the server ok, but the callback function wasn't called again. I didn't see any Javascript errors either. Turned out I had my onreadystatechange and open calls in the wrong order. This is how they were:

request.onreadystatechange = updatePage;
request.open("GET", url, true);
request.send(null);

When I made the following change, it worked.

request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);

Another fix was when I had the code to make a request inside a single function and being called before the three request lines, like below. Obviously, this was just hiding the problem though.

<script type="text/javascript">
function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  }

  if (request == null) {
    alert("Error creating request object!");
  }
}

function doAjaxyThing() {
  var url = "...";
  createRequest();
  request.onreadystatechange = updatePage;
  request.open("GET", url, true);
  request.send(null);
}
</script>

3 comments: