title: javascript callback function, onreadystatechange, in a simple ajax example
body: <p>I'm doing this tutorial in ajax and I don't understand one of the lines where a function is called. (line 6 in the code)</p>
  
  <pre><code>// this is called from an onload event in the html body  tag
  function process() {
      if (xmlHttp) {
          try {
              xmlHttp.open("GET", "hello.txt", true);
              xmlHttp.onreadystatechange = handleServerResponse; ***** THIS LINE HERE
              xmlHttp.send(null);
          } catch(e) {
              alert(e.toString());
          }
      };
  }
  
  handleServerResponse = function() {
      theD = document.getElementById('theD');
  
      if (xmlHttp.readyState == 1) {
          theD.innerHTML += "Status 1: server connectino established &lt;br /&gt;";
      } else if (xmlHttp.readyState == 2) {
          theD.innerHTML += "Status 2: request recieved &lt;br /&gt;";
      } else if (xmlHttp.readyState == 3) {
          theD.innerHTML += "Status 3: server processing task &lt;br /&gt;";
      } else if (xmlHttp.readyState == 4) {
          if (xmlHttp.status == 200) {
              try {
                  text = xmlHttp.responseText;
                  theD.innerHTML += 'status 4: request completed, response delievered.';
                  theD.innerHTML += '&lt;br /&gt;' + text;
              } catch(e) {
              }
          } else {
              alert("request cannont be completed by server (status 4)");
          };
      };
  }
  </code></pre>
  
  <p>why wouldn't I call it with parenthesis? like: <code>xmlHttp.onreadystatechange = handleServerResponse();</code></p>
  
  <p>when I do this it only seems to call the function once as it only prints out status 2. without the brackets though, when the function is declared as variable it seems to be called each time the state changes. why is this?</p>
  
  <p>Also, why does the xmlHttp.onreadystatechange property execute more than once? the body tag should only be loaded once, thereby calling the function only once. why is it looping?</p>
  
  <p>I'm definitely missing something, either with the ajax related objects or javascript function calling.</p>
  
  <p>apart from the answer below, here is a good explanation of the "true" and "null" parameters in the process function: <a href="http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp" rel="nofollow">http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp</a></p>