Question

I am trying to use $.post to send form data to a server side script to be saved if the user tries to leave the page without submitting the form. I am using the same function attached to a save button and on setInterval set to every 2 minutes, and it works fine. But when I attach the function to document.onbeforeunload it does not work. In firebug, I see the request is being sent, but it looks like it is being stopped before a status code is returned and the page continues to unload. I am still pretty new to Javascript and Jquery and I am not sure if maybe $.post is one of those functions that might not work on the onbeforeunload event. If that is true, is there another way I can send the data if the user tries to leave the page without saving?

This is the function I am calling from the onbeforeunload event:

           function ajaxSubmit(){
                var blogtitle = $("#title").val();
                var publishedstate = 0;
                var blogid = $("#blogID").val();
                var blogbody = CKEDITOR.instances['body'].getData();

                var postdata = {ajaxSubmit:true,title:blogtitle,body:blogbody,published:publishedstate,blog_id:blogid};
                $.post('ajaxblog.php',postdata,function(data){
                    $("#autosaveMessage").html(data);
                    $("#autosaveMessage").show();
                    setTimeout(function(){$("#autosaveMessage").hide();},5000);
                });
            }

and this is how I am calling the function:

               var post_clicked = false;
            $("#postButton").click(function(){
                post_clicked = true;
            });

            function leaveEditor(){
                if(post_clicked==false){
                    ajaxSubmit();
                }
                else{
                    //Do Nothing
                }
            }

window.onbeforeunload = leaveEditor;
Was it helpful?

Solution

No, and this is by design. It would be remarkably troublesome if a page could use onbeforeunload to indefinitely delay browsing away, persist its presence somehow, etc. One of the most important abilities for a user of a web browser to have is the ability to leave.

Just use the stringy return value—the whole point of it is to remind the user that s/he made changes that will be lost. Like on SO :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top