title: Javascript - AJAX call within a unload/pagehide event
body: <p>With our web application, a call to the server using ajax with a 'kill' operation attached must be made when the user exits/closes the window. However, either the unload/pagehide event is not being fired, or the ajax call is not being executed and I have been unable to determine as to why...</p>
  
  <p>Context:</p>
  
  <ul>
  <li>Unfortunately, we must use vanilla js; no jQuery.</li>
  <li>I am well aware of onbeforeunload, but for various cases, the ajax call cannot occur within that event (unless there is some magical
  hack that I am not aware of that suppresses the default popup box
  and/or provides a way to see user response).</li>
  <li>We must have compatibility for IE7+, FF14+. No need to support Chrome, Safari, Opera.</li>
  <li>I know the ajax functionality works - it is called numerous times while the browser is active and has been thoroughly tested.</li>
  </ul>
  
  <p>Relevant code...</p>
  
  <p>Code from the .jsp:</p>
  
  <pre><code>if (window.onpagehide || window.onpagehide === null) {
      addEvent(window, 'pagehide', kill);
  } else {
      addEvent(window, 'unload', kill);
  }
  </code></pre>
  
  <p>Code from utils file:</p>
  
  <pre><code>function addEvent(obj, evt, fnc) {
  
      if (obj.addEventListener) { //W3C
          obj.addEventListener(evt, fnc, false);
          return true;
      } else if (obj.attachEvent) { // MSFT
          return obj.attachEvent('on' + evt, fnc);
      } else { // Legacy
  
          evt = 'on'+evt;
  
          if(typeof obj[evt] === 'function') {
  
              // Object already has a function on traditional
              // Let's wrap it with our own function inside another function
              fnc = (function(f1, f2) {
                  return function() {
                      f1.apply(this, arguments);
                      f2.apply(this, arguments);
                  }
              })(obj[evt], fnc);
          }
  
          obj[evt] = fnc;
          return true;
      }
  
      return false;
  };
  
      function kill() {
  
          ajax.post({
              "refCallback": null,
              "sURL": "--deleted--",
              "async": false,
              "timeout": 10000,
              "params": {"op": "kill",
                          "guid": guid}});
  
      };
  </code></pre>
  
  <p>Any insight or pointers will be extremely helpful...</p>