title: Assigning javascript function with parameters to a variable gets instantly called
body: <p>I'm trying to make a <code>xmlHttpRequest</code> before the page body loads. When trying to assign the <code>onreadystatechange</code> function, this one gets called <em>instantly</em>, thus returning <code>xmlHttp.readyState</code> <strong>always to 0</strong>.</p>
  
  <p>I supose I'm making the call in a wrong way. How am I supposed to assign the function correctly?</p>
  
  <pre><code>//create xmlHttp object
  function CreateXmlHttp() {
      try {
          var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch(e) {
          try {
              xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
          } catch(eo) {
              xmlHttp = null;
          }
      }
      if(!xmlHttp &amp;&amp; typeof XMLHttpRequest != "undefined") {
          xmlHttp = new XMLHttpRequest();
      }
      return xmlHttp;
  }
  
  //request call
  function post(url, func, XML) {
      var xmlHttp = CreateXmlHttp();
      //problem?
      xmlHttp.onreadystatechange = (function (xmlHttp, func) {
          if(xmlHttp.readyState == 4 &amp;&amp; xmlHttp.status == 200) {
              func(xmlHttp.responseText);
          }
      })(xmlHttp, func);
      xmlHttp.open("POST", url, true);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
      if(XML==null){
          XML = '';
      }
      xmlHttp.send(XML);
  }
  
  post('/json/checklogged', function (data) {
      var jsonData = eval("(" + data + ")"); //I know, this eval is dangerous
      if(jsonData.logged){
          var url = '${nextUrl}';
          post(url, function(data){
              document.open();
              document.write(data);
              document.close();
          });
          history.pushState({}, '', url);
      }
  });
  </code></pre>