javascript - Call Ajax on unload if user clicks "OK" -


i'm designing rather long form auto-save every couple minutes (i.e., using ajax, form data inserted or updated mysql database). however, if user decides exit page before submitting form, want make sure delete row inserted database. do-able if user clicks link or form's cancel button. i'm concerned happens when user: 1) closes page, 2) reloads page, or 3) hits browser's (or forward) button. know how use unload event create confirmation dialog asking user confirm want leave page. don't know how make ajax call (to delete row database) if user clicks ok ("press ok continue"). there way call function if user clicks ok button during unload event?

window.onbeforeunload = function() {     if ($('#changes_made').val() == 'yes') //if user (partially) filled out form         {             return "are sure?"             if (/*user clicks ok */)  //what should if statement evaluate here?             {                 //make ajax call             }         } }; 

$(document).ready(function() {        $(':input',document.myform).bind("change", function() {         setconfirmunload(true);      }); // prevent accidental navigation away });  function setconfirmunload(on) {      // avoid ie7 , prior jquery version issues         // directly using window.onbeforeunload event      window.onbeforeunload = (on) ? unloadmessage : null; }  function unloadmessage() {      if(confirm('you have entered new data on page.  if navigate away page without first saving data, changes lost.')) {              $.ajax({                type: "post",                url: "some.php",                data: "name=john&location=boston",                success: function(msg){                  alert( "data saved: " + msg );                }              });      }  } 

make sure have upgraded version of jquery. jquery version 1.3.2 had bug:

ticket #4418: beforeunload doenst work correctly

or use native function:

window.onbeforeunload = function() {....} 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -