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:
window.onbeforeunload = function(e){
var noteelement = document.getElementById( 'note' );
var mynote = noteelement.value;
$.post('save_my_note.php', { thenote: mynote }, function(data){});
};
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.
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:
$.post('save_my_note.php', { thenote: mynote }, function(data){});
return mynote;
};
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:
$.ajax({
url: "save_my_note.php",
data: "{thenote: mynote}",
async: false
});
However, that just doesn't seem to work either.
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.