Ajax Troubleshooting Tips

  1. Always test your assumptions about where you think you are in your Javascript code. The easiest way to do this is to use alert functions that let you know where you are and what values certain variables have at that point. See page 59 in the textbook for examples.
  2. Recheck the spelling (including the correct case) for names of objects, properties, methods, and functions. Follow these standards to avoid mistakes:
  3. If you know that a callback function is not getting called because an opening alert is not displayed then set the callback to do the alert directly. Here is an example for the window's onload property:
    Try this first If it doesn't work try this
    window.onload = initPage;
    function initPage() {
       alert("got here");
       ...
    window.onload = alert("got here");
    function initPage() {
       ...
    If the direct callback works then your Javascript code may have a syntax error that you need to find. Comment out sections of the Javascript code until alerts in the callback function start to work again. Then converge on the offending code by commenting out smaller and smaller sections until the alerts stop working.
  4. A common and difficult error to recognize in your Javascript code is found in conditional expressions in which a single = symbol is used to test for equality. That is interpreted as an assignment operation which destroys the old value of the variable on the left-hand-side of the expression. Page 70 of the textbook has such an error:
    Problematic Javacode Alternative way to avoid this problem
    function checkUserNames() {
      request = createRequest();
      if (request = null)
        alert("Unable to create request");
      else
      { ...
        request.onreadystatechange=checkUserName;
        ...
      }
    }
    function checkUserNames() {
      request = createRequest();
      if (request)
      { ...
        request.onreadystatechange=checkUserName;
        ...
      }
      else
        alert("Unable to create request");
    }
    On line 3 a request object is created, but on line 4 the request variable is reset to be null. The assigned value is the value of this Boolean expression and since it is null it is treated as false (similarly for values of 0, undefined, NaN, or the emptystring). Thus, the program continues with the else clause and erroneously refers to the onreadystatechange property of a null object. The Javascript interpreter in a browser may quit running the script at that point, whereas a different browser may ignore the line and keep on going (which complicates troubleshooting).

    The alternative code above avoids a formal equality test since a null value is interpreted as being false. Enclosing the single alert statement in curly-brackets would be advisable, especially now that it is in an else clause which is buried further down in the code.