title: Call a JavaScript function when user leaves a page
body: <p>I want the function <code>pageleave()</code> to be called before the user exits a page. But I can't seem to get it to work correctly, I searched the web for a couple hours and can't find a solution. Here is the code I came up with. It runs when the page loads instead of when the page unloads.</p>
  
  <pre><code>window.onbeforeunload = pageleave;
  
          function pageleave() {
              $.post("&lt;?php echo dirname( get_bloginfo('stylesheet_url') ); ?&gt;/ajax/videocanle.php", { videoID: "&lt;?php echo $videoID; ?&gt;" },
                  function(data) {
                      if ( data != "\nsuccess"){
                          alert ("Sorry but there was an unexpected error, please try again");
                      }
  
                  });
  
          }
  </code></pre>
  
  <p>That is the current revision, it still doesn't run the function before the page unloads. The function does work thou, I tested it with a simple input button. </p>
  
  <pre><code>&lt;input type="button" value="test function" onclick="pageleave()" /&gt;
  </code></pre>