title: Using Ajax in onbeforeunload to autosave field data
body: <p>I am trying to use AJAX in the window.onbeforeunload function to autosave a text field that is on a page in my site (there is no save button, it is all done in the background).  The saving function is written in PHP.  I started by trying the following:</p>
  
  <pre><code>window.onbeforeunload = function(e){
    var noteelement = document.getElementById( 'note' );
    var mynote = noteelement.value;
  
    $.post('save_my_note.php', { thenote: mynote }, function(data){});
    };
  </code></pre>
  
  <p>In researching, I have come to understand that due to the asynchronous nature of the ajax call, the php code is not called because the window closes before the function fires off from the server.</p>
  
  <p>Of course, as others have said, if I add a return value to onbeforeunload function to cause the dialog box to pop up (that would be the "are you sure you want to leave" box), it DOES work since the .post call has the time to get run while the dialog box waits for a response:</p>
  
  <pre><code>  $.post('save_my_note.php', { thenote: mynote }, function(data){});
    return mynote;
    };
  </code></pre>
  
  <p>It has been said that I have to change this post call to asynchronous AJAX so that the function waits for the function to complete, but not being very versed in the syntax, I am not quite sure of the syntax I need.  I tried the following in place of the post function:</p>
  
  <pre><code>        $.ajax({
              url: "save_my_note.php",
              data: "{thenote: mynote}",
              async: false                 
          });
  </code></pre>
  
  <p>However, that just doesn't seem to work either.  </p>
  
  <p>Does anyone have a simple code example for implementing the autosave in a synchronous manner via the onbeforeunload (or the onunload??) function?  I'm not a javascript or jquery expert, and the examples I have found online have been confusing. </p>